Author Posts

August 29, 2017 at 12:59 pm

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

August 29, 2017 at 1:16 pm

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

August 29, 2017 at 1:51 pm

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