Output is not correct

Welcome Forums General PowerShell Q&A Output is not correct

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

 
Participant
1 year, 3 months ago.

  • Author
    Posts
  • #78281

    Participant
    Points: 2
    Rank: Member

    I need help with this script. I am getting double entries in the output for few users. when script catch the error in the catch block of script. It create double entry for the user below in the text file.

    Import-Module ActiveDirectory
    $UserList = Get-Content C:\UserList.txt
    $infoobj = @()
    foreach ($user in $UserList) {
    Try {
    $UserInfo = Get-ADUser -Identity $User -Properties * -ErrorAction stop
    }
    Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
    Write-Output "$($_.TargetObject)" | Out-File C:\UserNotFound.txt -Append
    }

    Finally {
    $Prop = [Ordered]@{

    'User Name' = $UserInfo.name
    'eTenet ID' = $UserInfo.Samaccountname
    'EmployeeID'= $UserInfo.EmployeeID
    'LastLogonTimeStamp' = $(([DateTime]::FromFileTime($UserInfo.lastLogonTimestamp)))}

    $InfoObj += New-Object PSObject -Property $Prop
    $infocall = $infoobj
    }
    }
    Write-Output $Infocall

  • #78287

    Participant
    Points: 0
    Rank: Member

    Because your line
    $UserInfo = Get-ADUser -Identity $User -Properties * -ErrorAction stop

    doesn't work when the user isn't found

    $Prop = [Ordered]@{
    'User Name' = $UserInfo.name
    'eTenet ID' = $UserInfo.Samaccountname
    'EmployeeID'= $UserInfo.EmployeeID
    'LastLogonTimeStamp' = $(([DateTime]::FromFileTime($UserInfo.lastLogonTimestamp)))}
    $InfoObj += New-Object PSObject -Property $Prop
    $infocall = $infoobj
    }
    

    uses the information from the last successful call

    something like this should work

    $UserInfo = $null
    Try {
    $UserInfo = Get-ADUser -Identity $User -Properties * -ErrorAction stop
    }
    Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
    Write-Output "$($_.TargetObject)" | Out-File C:\UserNotFound.txt -Append
    }
    if ($userinfo) {
    $Prop = [Ordered]@{
    'User Name' = $UserInfo.name
    'eTenet ID' = $UserInfo.Samaccountname
    'EmployeeID'= $UserInfo.EmployeeID
    'LastLogonTimeStamp' = $(([DateTime]::FromFileTime($UserInfo.lastLogonTimestamp)))}
    $InfoObj += New-Object PSObject -Property $Prop
    $infocall = $infoobj
    }
    }
    
    • #78299

      Participant
      Points: 2
      Rank: Member

      Your script is working
      Thank you very much Richard...

The topic ‘Output is not correct’ is closed to new replies.