Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv | ForEach { Get-ADComputer -identity $_.computer -properties * | select CN, extensionAttribute1, created, Description, DistinguishedName, enabled } | export-csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Hi, how i can change my PS script. If user from CSV not found then paste NAME;"NOT_FOUND", now my script just skip users that were not found with errors.
CodePudding user response:
What you could do is a try/catch block, so that if an error occurs (when it does not exists) it outputs not found for the value "CN".
Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv | ForEach {
$computer = $_.computer
try{
Get-ADComputer -identity $computer -properties *
}catch{
@{
CN = "$computer not found"
}
}
} | select @{n="CN";e={$_.CN}}, extensionAttribute1, created, Description, DistinguishedName, enabled | Export-Csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Or as your less readable one-liner:
Import-CSV -Path C:\Users\*******\Desktop\Powershell\Input.csv | ForEach {try{Get-ADComputer -identity $_.computer -properties *}catch{@{CN = "Not found"}}} | select @{n="CN";e={$_.CN}}, extensionAttribute1, created, Description, DistinguishedName, enabled | export-csv -path C:\Users\*******\Desktop\Powershell\Output.csv -Append -Encoding UTF8 -Delimiter ";"
Note that at the select we use an expression. It says name (n)="CN";expression (e)=$_.CN which is the CN and in case of an error it consists of the value "not found" from the catch block. You can also choose to add this expression to more/different values of the select statement if you enrich the object at the catch block. Or use if/else in the expression.