Reputation: 75
I'm trying to determine which user folders in C:\Users have active users in Active Directory.
I currently have the following:
$userProfile = Get-ChildItem -Path "C:\Users"
$unknownList = @()
foreach($user in $userProfile){
try{
Get-ADUser -Identity $user.Name | Out-Null
}
catch{
$unknownList += $user.Name
}
}
Write-Host $unknownList
My issue is that all usernames appear to not exist and are caught. Can anyone offer some suggestions for a PowerShell first-timer? I have a tried a number of other things found here and elsewhere but none have been able to work. Thank you!
Upvotes: 1
Views: 16494
Reputation: 13523
I was wanting to do something similar, and was appalled that it seemed like the only way to see if a user exists in AD was to barbarically have the Get-ADUser throw an error, and you then catch it. After much research, I found that instead of using the -Identity
parameter if you use the -Filter
parameter you actually get back, either the user object(s) that match the filter parameter, or a $Null object (because nothing matches the -Filter
parameter). Once you have that in a variable, you can then do a "proper" if/else statement evaluation without throwing any errors.
Here is your code:
$userProfile = Get-ChildItem #-Path "C:\Users"
$unknownList = @()
foreach($user in $userProfile){
#Try getting the user
$ADUser = Get-ADUser -Filter {SamAccountName -eq $User.Name}
#Test to see if the user exists
If($ADUser)
{
#User Exists
#Write-host "$($User.Name) Exists"
}
Else
{
#User does not Exist
#Write-host "$($User.Name) Does not Exist"
Write-host "$($User.Name)"
}
}
Upvotes: 7