I have a file with a list of computers, I need to loop through that list and report if one is free.
$list = get-content "pathtofile.txt"
foreach ($computer in $list) {
try {
quser /server:$computer
} catch [System.Management.Automation.RemoteException] {
Write-Host "$computer is free"
}
}
Now it works, but I want the catch to grab the error message and change it to the mess of computer name is free.
At the moment it is still returning
quser : No User exists for *
At line:5 char:5
+ quser /server:$computer
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
For computers that are free.
I was able to get the System.Management.Automation.RemoteException by running the quser command against a computer I know is free and then running $Error[0] | fl * -Force:
writeErrorStream : True
PSMessageDetails :
Exception : System.Management.Automation.RemoteException: No User exists for *
TargetObject : No User exists for *
CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 1
PipelineIterationInfo : {0, 0}
Which gave me the exception code.
Now I did look at Foreach error handling in Powershell which showed my code should be right so not sure why the catch is not working.