Get-ADUser Script - Help with Error Handling

I have a script that I run that will take a list of users (listed by DisplayName) in a CSV file that will import the ActiveDirectory module & use Get-ADUser to produce another CSV with more details like the first name, last name, samAccountName and eMailAddress.

I cobbled together this little script by adapting one I found online somewhere (I don’t remember where now). My only problem is that if there is a typo in the display name in the first CSV, I don’t get any sort of error: the line for that account is just missing in the output CSV created by the script.

Is there a way to force PowerShell to put some sort of error like “account not found” or something to indicate there’s an issue? usually, I got the wrong display name in the ticket like “Smith, Cathy” instead of how it appears in AD like “Smith, Catherine.”

The way it is now, I have to just go line by line to make sure the script got all the user accounts before I send back the list of user accounts & email addresses. That works fine when there are just 5 or 10 AD accounts listed, but not so much when there’s like 50.

Here’s the script:

[pre]

Import-Module ActiveDirectory
$Sam = @()
$names = Import-csv “C:\Tools\Powershell\LoginIDs.csv”

foreach ($name in $names.displayname)
{
$sam += get-aduser -filter {name -like $name} -properties * | Select Name, GivenName, SurName, samAccountName, eMailAddress

}

$Sam | Export-Csv C:\Tools\Powershell\LoginIDs-Out.csv -NoTypeInformation

[/pre]

 

Thanks in advance!

Alicia

Sounds like you need to use a try/catch block.

Give this a try:

 

foreach ($name in $names.displayname)
{
try {
$sam += get-aduser -filter {name -like $name} -properties * -ErrorAction Stop | Select Name, GivenName, SurName, samAccountName, eMailAddress
} catch {
write-warning "$name NOT FOUND"
}
}

Darwin,

Where should I see that warning “$name NOT FOUND”? I added that block you gave me to the script I have & I am still getting nothing for those display names with typos. Just like before, I don’t even get a blank line: it just skips over the misspelled display name & gives me the next one in the list.

 

Try this:

foreach ($name in $names.displayname)
{
try {
$sam += get-aduser -filter {name -like $name} -properties * -ErrorAction Stop | Select Name, GivenName, SurName, samAccountName, eMailAddress
} catch {
$name|out-file -append Failed.txt
}
}

That will create a list of the failed names.

There one method which i can think
$script:result=@()
foreach ($name in $names.displayname)
{
$sam = get-aduser -filter {name -like $name} -properties * -ErrorAction silentlycontinue -errorvariable adusererror
if($adusererror -eq $null){ 
$hasherror=[PSCustomObject]@{
Name = $name
GivenName=$null
SurName=$null
samAccountName=$null
eMailAddress=$null
error="Account is not Found"}
$script:result+=$hasherror

}else {
$hash=[PSCustomObject]@{
Name = $sam.name
GivenName=$sam.GivenName
SurName=$sam.SurName
samAccountName=$sam.samAccountName
eMailAddress=$sam.eMailAddress
error=$null}
$script:result+=$hash
}
}
$adusererror=$null
}
$script:result | Export-Csv C:\Tools\Powershell\LoginIDs-Out.csv -NoTypeInformation

That didn't work, either and the error output, Failed.txt, isn't created by the script when I add that block to it.

Evila Osa,

I inserted that into my script & got a bunch of text like this & no output CSV file at all:

[pre]

At C:\Tools\PowerShell\LoginIDs-TEST.ps1:15 char:12

  • Name=$name,
  • ~
    Missing expression after ‘,’.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:17 char:1
  • GivenName=$null,

Unexpected token ‘GivenName=$null’ in expression or statement.
At C:\Tools\PowerShell\LoginIDs-TEST.ps1:15 char:12

  • Name=$name,
  • ~
    The hash literal was incomplete.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:17 char:16
  • GivenName=$null,
  • ~
    Missing argument in parameter list.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:33 char:16
  • Name=$sam.name,
  • ~
    Missing expression after ‘,’.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:35 char:1
  • GivenName=$sam.GivenName,

Unexpected token ‘GivenName=$sam.GivenName’ in expression or statement.
At C:\Tools\PowerShell\LoginIDs-TEST.ps1:33 char:16

  • Name=$sam.name,
  • ~
    The hash literal was incomplete.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:35 char:25
  • GivenName=$sam.GivenName,
  • ~
    Missing argument in parameter list.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:49 char:1
  • }
  • ~
    Unexpected token ‘}’ in expression or statement.
    At C:\Tools\PowerShell\LoginIDs-TEST.ps1:53 char:1
  • }
  • ~
    Unexpected token ‘}’ in expression or statement.
  • CategoryInfo : ParserError: (:slight_smile: , ParentContainsErrorRecordException
  • FullyQualifiedErrorId : MissingExpressionAfterToken

[/pre]

Interestingly the get-aduser with the filter doesn’t throw an error when the user isn’t found. So the try/catch block won’t work. I just ran this on a small subset of users (4 accounts)

I’m not terribly proud of this script, but it did give me the results I expected. Basically before it writes to the CSV file, it looks for the samaccountname, if there’s none it’ll write the displayname to the failed file, if it finds the samaccount name it keeps executing.

foreach ($name in $names.displayname){
$present=(get-aduser -filter {name -like $name}).samaccountname
if ($present -ne $null){
get-aduser -filter {name -like $name} -properties *| Select Name, GivenName, SurName, samAccountName, eMailAddress |export-csv  -append -notypeinformation outfile.csv
} else {$name|out-file -append Failed.txt
}
}
thanks! that worked! I was getting 3 copies of all the data for some reason with that script block added to mine (after the $names line that specifies the input CSV).

Here’s what I did to tweak it and this does produce outfile.csv and Failed.txt files.

[pre]

Import-Module ActiveDirectory
$Sam = @()
$names = Import-csv “C:\Tools\Powershell\LoginIDs.csv”

foreach ($name in $names.displayname){
$present=(get-aduser -filter {name -like $name}).samaccountname
if ($present -ne $null){
$sam += get-aduser -filter {name -like $name} -properties * | Select Name, GivenName, SurName, samAccountName, eMailAddress | `
export-csv -append outfile.csv -notypeinformation
} else {$name|out-file -append Failed.txt
}
}

[/pre]

You don’t really need the

$sam +=

any longer, since you’re exporting to CSV as the script runs. Keeping it doesn’t harm anything, but its optional.

I made a bad assumption at first, that the get-aduser with filer will throw an error when the user isn’t found. My guess is that the command runs successfully, just there’s nothing in the filter. In hindsight it makes sense.

Because this script is a bit different, instead of overwriting the existing file, it just keeps appending the results in those 2 output files, which is not what I want: I don’t need to keep the old results. I just want current results.

So, I added a few lines to check for those files & delete them if they exist.

Here’s the final script. Thanks everybody!

[pre]

cd \Tools\PowerShell

Import-Module ActiveDirectory
$Sam = @()
$names = Import-csv “LoginIDs.csv”

$FileName = “Failed.txt”,“LoginIDs-Out.csv”

if (Test-Path $FileName)
{
Remove-Item $FileName
}

foreach ($name in $names.displayname)
{
$present=(get-aduser -filter {name -like $name}).samaccountname
if ($present -ne $null)
{
$sam += GET-ADUser -Filter {name -like $name} -properties * | Select Name, GivenName, SurName, samAccountName, eMailAddress | `
Export-Csv -append LoginIDs-Out.csv -NoTypeInformation
}
else
{$name | out-file -append Failed.txt}
}

[/pre]

Ya i come to know about the error which i have corrected as well.

an0nemus09, you said about the script:

since you're exporting to CSV as the script runs
Can we make it so it exports to CSV at the end rather than as it runs? If I take out the "-append" option in the new version of the script, I only get one name listed in each of the resulting files. So that's why I added those lines at the beginning to delete the output files if they exist before the script runs.

I made this script because I sometimes get an email asking for the userIDs and/or email addresses for a list of employees. That list of employees is usually sent using their the “Last Name, First Name” format, which is usually identical to the display name in AD. Rather than painstakingly copying/pasting from AD, I wanted to speed up the process so I created that little script to automate the process of turning a list of display names to a list of UserIDs and email addresses.

So, I don’t really care about any previous results and would prefer that the script just overwrote the existing files with new results every time it’s run.

Thanks for all your help on this,

Alicia