# Check For Existing AD Users

**URL:** <https://forums.powershell.org/t/check-for-existing-ad-users/12502>\
**Category:** PowerShell Help\
**Created:** [May 3, 2019, 8:09am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502 "2019-05-03T08:09:37Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![chm0d](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/chm0d/32/34_2.png) [@chm0d](https://forums.powershell.org/u/chm0d)\
**Post date:** [May 3, 2019, 8:09am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/1 "2019-05-03T08:09:37Z")

</div>

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."
    }
		
}
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/1X/385e4f9fe133561ad30a814262fe0e0ae6bc3ef0.png) [@system](https://forums.powershell.org/u/system)\
**Post date:** [May 3, 2019, 8:16am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/2 "2019-05-03T08:16:50Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![chm0d](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/chm0d/32/34_2.png) [@chm0d](https://forums.powershell.org/u/chm0d)\
**Post date:** [May 3, 2019, 8:32am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/3 "2019-05-03T08:32:47Z")

</div>

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.

&nbsp;

Rich

---

<div class="post-metadata">

**Author:** ![an0nemus](https://avatars.discourse-cdn.com/v4/letter/a/e9bcb4/32.png) [@an0nemus](https://forums.powershell.org/u/an0nemus)\
**Post date:** [May 3, 2019, 10:37am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/4 "2019-05-03T10:37:18Z")

</div>

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
}
}
```

---

<div class="post-metadata">

**Author:** ![pwshliquori](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/pwshliquori/32/222_2.png) [@pwshliquori](https://forums.powershell.org/u/pwshliquori)\
**Post date:** [May 3, 2019, 10:42am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/5 "2019-05-03T10:42:13Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![postanote](https://avatars.discourse-cdn.com/v4/letter/p/ebca7d/32.png) [@postanote](https://forums.powershell.org/u/postanote)\
**Post date:** [May 3, 2019, 6:39pm UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/6 "2019-05-03T18:39:21Z")

</div>

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"
```

---

<div class="post-metadata">

**Author:** ![chm0d](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/chm0d/32/34_2.png) [@chm0d](https://forums.powershell.org/u/chm0d)\
**Post date:** [May 6, 2019, 5:20am UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/7 "2019-05-06T05:20:50Z")

</div>

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."
    }
		
}
```

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:32pm UTC](https://forums.powershell.org/t/check-for-existing-ad-users/12502/8 "2024-05-16T20:32:52Z")

</div>


