Check For Existing AD Users

I have been trying to wrap my head around this all morning and getting frustrated. It is usually something pretty stupid and I am new to powershell. I have a CSV file of users. The script works fine outputting everything in the console whether a user exists in AD or not. I would like that output of just existing users in a txt file, csv, it doesn’t matter, but I just can’t seem to get it. In the script below I have tried to replace my Else statement with Out-File and it creates the file but its blank. Any help would be greatly appreciated.

# Access Active Directory PowerShell Commands.
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
# Import List Of Accounts From CSV.
$ListOfAccounts=IMPORT-CSV E:\ADMP\DataPullJim2.csv
FOREACH ($Account in $ListOfAccounts)
{
    
    # If the account exists, inform, if it does not exist also inform.
    $Username = $Account.Username
    If ((Get-ADUser -Filter {Name -eq $Username }) -eq $Null)
	
    {
        Write-Host "I am sorry, $Username does not exist."
    }
    Else
    {
       Write-Host "Looks like $Username already exists in Active Directory."
    }
		
}

Your Get-ADUser command is going to result in True or False without the need to compare anything to $null. That part’s not needed. Remove $null and the second set of parenthesis around it. Then, switch your Write-Host values. If your Get-ADUser command results in True, you want it to indicate the username already exists, and if your Get-ADUser command results in False, you want to indicate the username does not exist.

Thank you for the reply! Removing the $null only forces me to change the write-host the opposite of what they are now. The top write-host would be that they exist in AD and the bottom they do not. This doesn’t help me as far as getting the output to a text file. Sorry if I am misunderstanding what you posted.

 

Rich

Something like this should work:

It assumes that the value in the spreadsheet is the samaccountname

foreach ($a in $loa){
try {
get-aduser -identity $a -erroraction stop
$a |out-file -append there.txt
} catch {
$a |out-file -append notthere.txt
}
}

If I understand correctly, you just want the existing users in AD to output to a file. If so, can you try the following:

$ListOfAccounts=IMPORT-CSV E:\ADMP\DataPullJim2.csv

$ListOfAccounts.Username |Foreach-Object {
    Try {
        Get-ADUser -Identity $_ |Select-Object -ExpandProperty SamAccountName -ErrorAction Stop |Out-File -FilePath C:\Temp\ADUsers.txt -Append
    }
    Catch {
        Write-Output "User does not exist" # Or output whatever you want to console.
    }
}

Unless you need to specify the Where-Object, in that case, you will need the if else statement as filtering has a null output and not an error.

Also, in your original script, try not to use -eq $null, use (!(Get-ADser)) or (-not(Get-ADUser))

pwshliquori

Depending on what OS version and PS version you are on, why are you not using the cmdlet specifically designed for this…

# get function / cmdlet details
(Get-Command -Name Search-ADAccount).Parameters.Keys | Sort
Get-help -Name Search-ADAccount -Full
Get-help -Name Search-ADAccount -Online
Get-help -Name Search-ADAccount -Examples

Function Get-HelpExamples
{
    [CmdletBinding()]
    [Alias('ghe')]

    Param
    (
        [string]$CmdletName = (
            Get-Command -Name '*' | 
            Out-GridView -PassThru -Title 'Select a cmdlet to see examples'
        )
    )

    If ((Get-Help -Name $CmdletName).Examples)
    {
        (((Get-Help -Name $CmdletName).Examples | 
        Out-String -Stream) -match '.*\\>|C:\\PS>') -replace '.*\\>|C:\\PS>' | 
        Out-GridView -Title 'Select a sample to use' -PassThru
    }
    Else {Write-Warning -Message "The were no help examples discovered"}
}

ghe -CmdletName Search-ADAccount

# Results

Search-ADAccount -AccountDisabled | FT Name,ObjectClass -A
Search-ADAccount -AccountDisabled -UsersOnly | FT Name,ObjectClass -A
Search-ADAccount -AccountExpired | FT Name,ObjectClass -A
Search-ADAccount -AccountExpiring -TimeSpan 6.00:00:00 | FT Name,ObjectClass -A
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | FT Name,ObjectClass -A
Search-ADAccount -PasswordExpired | FT Name,ObjectClass -A
Search-ADAccount -PasswordNeverExpires | FT Name,ObjectClass -A
Search-ADAccount -LockedOut | FT Name,ObjectClass -A
Search-ADAccount -AccountDisabled -ComputersOnly | FT Name,ObjectClass -A
Search-ADAccount -AccountExpiring -DateTime "3/18/2009" | FT Name,ObjectClass -A
Search-AdAccount -AccountDisabled -SearchBase "DC=AppNC" -Server "FABRIKAM-SRV1:60000"

Thank you all for replying and the assistance. Coming into work with a fresh mind and help from a colleague we ended up finding code to give us what was needed. Below is what works for us:

# Access Active Directory PowerShell Commands.
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
# Import List Of Accounts From CSV.
$ListOfAccounts=IMPORT-CSV E:\ADMP\DataPullJim2.csv
FOREACH ($Account in $ListOfAccounts)
{
    
    # If the account exists, inform, if it does not exist also inform.
    $Username = $Account.Username
    If (Get-ADUser -Filter {Name -eq $Username}) 
	
    {
	   $account | Select Username,SamAccountName | Out-File C:\temp\exist.txt -append 
	   Write-Host "$Username already exists in Active Directory" -ForegroundColor RED
	  }
    Else
    {
       Write-Host "I am sorry, $Username does not exist."
    }
		
}