Script to find Existing AD Users

Welcome Forums General PowerShell Q&A Script to find Existing AD Users

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
3 years, 3 months ago.

  • Author
    Posts
  • #28697

    Participant
    Points: 0
    Rank: Member

    Have this script to get me Existing AD user but how can I get results to a file

    $UserCSV = Import-Csv C:\temp\test.txt
    Foreach ($User in $UserCSV)
    {
    Try
    {
    # Use "EA Stop" to ensure the exception is caught.
    $U = Get-ADUser $User.sAMAccountName -ErrorAction Stop
    Write-output "$($User.SamAccountName) exist in domain"
    }
    Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
    {
    # The user was not found!
    Write-Warning "$($User.SamAccountName) was not found in this domain!"
    }
    Catch
    {
    # Some other terrible error occured!
    Write-Error "OHSHI"
    }
    }

  • #28699

    Participant
    Points: 1
    Rank: Member

    add this for example at the end of 'try' section

    $u.sAMAccountName | out-file -FilePath tmp.txt -Append

  • #28711

    Participant
    Points: 166
    Helping Hand
    Rank: Participant

    You could try an approach like this to just return a boolean (True\False) value if the user exists and forego the try\catch:

    $UserCSV = Import-Csv C:\temp\test.txt
    $results = $UserCSV | 
                    Select SamAccountName,
                    @{Name="AccountExists";Expression={[bool]([adsisearcher]("samaccountname={0}" -f $_.SamAccountName)).FindOne()}}
    
    $results | Where{$_.AccountExists -eq $true} | Select -ExpandProperty SamAccountName | Out-File C:\Test\usersThatExist.txt
    
  • #28712

    Participant
    Points: 166
    Helping Hand
    Rank: Participant

    You could try an approach like this to just return a boolean (True\False) value if the user exists and forego the try\catch:

    $UserCSV = Import-Csv C:\temp\test.txt
    $results = $UserCSV | 
                    Select SamAccountName,
                    @{Name="AccountExists";Expression={[bool]([adsisearcher]("samaccountname={0}" -f $_.SamAccountName)).FindOne()}}
    
    $results | Where{$_.AccountExists -eq $true} | Select -ExpandProperty SamAccountName | Out-File C:\Test\usersThatExist.txt
    
  • #28759

    Participant
    Points: 0
    Rank: Member

    Thank you for your help

The topic ‘Script to find Existing AD Users’ is closed to new replies.