Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing a CSV to a Share

Status
Not open for further replies.

mattleeprice

IS-IT--Management
Nov 29, 2019
1
US
Good Day,

We have several thousand users in our Active Directory. I have created a PS script to pull all of the users into a CSV file.

In a share we have folder for each user - about two thousand of these folders are old and need to be removed.

I would like to compare my CSV file of active users against the list of folder names in the share, listing all of the folders that are old and need to be removed.

I'm about at my wits end trying to get my script to run properly.

Any tips on a proper way to script this would be great.

Kindest Regards,

Matt
 
Matt
Are you still in need of assistance? I've been away for a while, but I'd be willing to help out, now, if I can.

If so, what would determine if a file was "old and need to be removed"? They don't show as a user in your AD user export?

Assumptions I'm making until I hear from you:
1. Directory names are equal to the users' SamAccountName
2. You have a SamAccountName attribute in the AD export

So, I think it would go something like this

Code:
$import = Import-Csv "C:\temp\user_export.csv"
$users = @()
foreach ($i in $import)
	{
	 $users += $i.SamAccountName
	}

#get directories$path = "c:\temp\userdirs\"
$dirs = Get-ChildItem -Path $path -Name

#find directories to remove
$removals = @()
foreach ($dir in $dirs)
	{
	 #directory is not in the list of users
	 if (!($users -contains $dir))
		{
		 #add dir to removal list
		 $removals += $dir
		}
	}
$removals | Out-file "C:\temp\remove_dirs.txt"

If you don't need to review the list you could remove them from the script instead of exporting them. You can add something like this into the if-statement:
Code:
if (!($users -contains $dir))
	{
	 #add dir to removal list
	 $removals += $dir
	 #remove directories
	 [COLOR=#EF2929][b]$dir2remove = $path+$dir
	 Remove-Item $dir2remove -Recurse -Force -Confirm:$False -EA SilentlyContinue[/b][/color]
	}




Light travels faster than sound. That's why some people appear bright until you hear them speak.
 
I see a typo in the first code block:
Code:
#get directories$path = "c:\temp\userdirs\"

Should be:
Code:
#get directories
$path = "c:\temp\userdirs\"



Light travels faster than sound. That's why some people appear bright until you hear them speak.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top