Insert "NoData" text into results as error handler for ObjectNotFound RRS feed

  • Question

  • I am looking to find a way to find a way to insert "NoData" into the Select-Object data to display in my resulting spreadsheet when the Get-AdUser results in the error : Cannot find an object with identity. The script is working, but I would like to have error handling. 

    $GroupExport1="c:\temp\Dipsam.xlsx" #raw dump with SamAcountName in A1
    $GroupExport2="C:\Temp\Users.txt"  #Removed SamAcountName from A1
    $GroupExport3="C:\Temp\email_Final.xlsx"  #Final Report with Displaynames
    Install-Module importexcel
    Import-Excel $GroupExport1 | Select-Object -ExpandProperty SamAccountName | Where{$_ -notmatch "SamAccountName"} | Out-File $GroupExport2
    (Get-Content $GroupExport2) | % {$_ -replace '"', ""} | out-file -FilePath $GroupExport2 -Force -Encoding ascii
    $users = ForEach ($user in $(Get-Content $GroupExport2)) {
    Get-AdUser $user -Properties SamAccountName,DisplayName,UserPrincipalName 
    $users |
    Select-Object SamAccountName,UserPrincipalName,GivenName,Surname,DisplayName |
    Export-Excel -Path $GroupExport3 -Show

    • Edited by WolfManJack1 Tuesday, October 16, 2018 11:41 PM remove
    Tuesday, October 16, 2018 11:32 PM

All replies

  • That cannot be done using an Identity.  It can be done using a Filter.

    if($user = Get-AdUser -Filter "SamAccountName -eq '$user'" -Properties SamAccountName,DisplayName,UserPrincipalName){


    Wednesday, October 17, 2018 12:17 AM
  • Here is how to do this in PowerShell.

    Install-Module importexcel
    Import-Excel c:\temp\Dipsam.xlsx | 
            if($user = Get-AdUser -Filter "SamAccountName -eq '$($_.SamAccountName)'" -Properties SamAccountName,DisplayName,UserPrincipalName){
                    SamAccountName = $_.SamAccountName
                    Status = 'No Data'
        } |
        Select-Object SamAccountName,Status, UserPrincipalName,GivenName,Surname,DisplayName |
        Export-Excel -Path C:\Temp\email_Final.xlsx -Show


    Wednesday, October 17, 2018 12:24 AM