Jason Amick Jason Amick - 3 months ago 12
PowerShell Question

Try Catch not as intended

So I have this script working except I cannot get the computer name to display when there is an error, I understand that is because the computer is offline and the first Get computername cmd is an error as well, but I have tried multiple ways to perform this function with one thing or another not working.

gc "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object{
Try{
$wdt = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_ -Ea Stop
$cdt = Get-Content "\\$_\C$\file\*.txt" -Ea Stop
}
Catch{
$wdt= $_
$cdt = 'Offline or NoFile'
}
$wdt | Select @{n='WorkStation';e={$_.PSComputerName}},@{n='Version';e={$cdt}}
} | ogv -Title 'Versions'
$host.enternestedprompt()


In a different attempt I have used this script, but this one below formats the information in rows instead of column like the first one.

Get-Content "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object {
Try{
@{ComputerName=$_}
@{Version = Get-Content "\\$_\C$\file\*.txt" -Ea Stop}
}
Catch{
@{Version = 'Offline or NoFile' }
}
} #| out-file \\localhost\c$\users\public\Desktop\version.csv


Any attempt to take my script and merge it with one someone suggested to me "the second one" breaks it completely. To reiterate the top script give me the format output in columns I want but the bottom script gives the catch error "ComputerName Error" I need but has the output in harder to read row outfile.

Any suggestions?
Thanks.

Answer

Inside the catch block, $_ no longer refers to the pipeline item, but to the error that was caught.

Assign $_ to a different variable and you can reuse it inside the catch block:

Get-Content "\\server\s$\powershellscripts\LabMachines\*.txt" | ForEach-Object{
    Try{   
        $ComputerName = $_
        $wdt = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName -Ea Stop
        $cdt = Get-Content "\\$_\C$\file\*.txt" -Ea Stop
    }
    Catch{
        $wdt = @{PSComputerName = $ComputerName}
        $cdt = 'Offline or NoFile'
    }
    $wdt | Select @{n='WorkStation';e={$_.PSComputerName}},@{n='Version';e={$cdt}}
}

Pipe to Export-Csv at the end if you want to output it to a CSV file:

} |Export-Csv C:\users\public\Desktop\version.csv -NoTypeInformation