简体   繁体   中英

Determine If Users Are In Active Directory With PowerShell

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!

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)"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM