Output is not correct

This topic contains 2 replies, has 2 voices, and was last updated by  Nitesh Parmar 3 months, 2 weeks ago.

  • Author
    Posts
  • #78281

    Nitesh Parmar
    Participant

    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

    Richard Siddaway
    Moderator

    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

      Nitesh Parmar
      Participant

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

You must be logged in to reply to this topic.