views:

431

answers:

2

Trying to determine if there are any user folders on the network that don’t have an associated user account. All results return "Missing" when the majority should return "Found". Any ideas?

$Dir = "\\ServerName\Share\"
$FolderList = Get-ChildItem($Dir) | where {$_.psIsContainer -eq $true}
$UserList = get-qaduser -sizelimit 0 | select LogonName

foreach ($Folder in $FolderList)
{
if ($UserList -contains $Folder.name)
{
"Found:  " + $Folder.name
}
Else
{
"Missing:  " + $Folder.name
}
}
+1  A: 

-contains will match if the item in the collection is identical to what you are testing so be sure that the $Folder.Name is exactly the same as LogonName. Usually it wouldn't be. Most companies would have the folder name be foo$ for a user named foo.

EBGreen
+2  A: 

How about trying a slightly different approach that uses a hashtable (which offers exceptionally fast lookups of keys):

$users = @{}
Get-QADUser -sizelimit 0 | Foreach {$users["$($_.LogonName)"] = $true}
$dir = "\\ServerName\Share\"
Get-ChildItem $dir | Where {$_.PSIsContainer -and !$users["$($_.Name)"]}

If the folder name doesn't exactly match the LogonName, then as EBGreen notes, you will need to adjust the key ($users["$($.LogonName)"]) or the folder name when you use it to index the hashtable (!$users["$($.Name)"]).

Keith Hill
Genius! Although I don't completely understand your code yet, it definitely works! Thanks to both of you for your input. Sorry i'm a Stack Overflow noob and can't vote you up yet!
Superfly
Essentialy the $users = @{} creates a hashtable (or dictionary). The second line populates that dictionary with all the user logon names and the value $true. Then in the last line, we scan each folder and check to see if it's name (not full path) is in the hashtable. If it is not then you have an orphaned folder.
Keith Hill
This is a much better solution. But your previous code does not work because $UserList actually contains a collection of PSObjects with a "LogonName" property. So your "if" statement is trying to compare a PSObject collection to a String, and thus not making a match. In any OO environment, you must be aware of what type of objects you are comparing. You can fix this by getting just the logon names instead: $UserList = get-qaduser -sizelimit 0 | for-each {$_.LogonName}
JasonMArcher