Reputation: 449
I am running following command remotely from PowerShell in Admin mode. This gets the status of App Pool (in IIS) from remote machine.
$result = Invoke-Command -ComputerName $servername -ScriptBlock {
param($appPoolName)
Get-WebAppPoolState -Name $appPoolName
} -ArgumentList $appPoolName | select value
If I am passing correct values I am getting proper data in $result
but if I am passing invalid server name, I am getting below error.
"Connecting to remote server failed with the following error message : WinRM cannot process the request."
The issue is I am not getting anything in $result
and even this is not going to Catch block. There is no way to identify if the command run successfully or not.
Please provide any pointers on how to get the command output in $result.
Note: I am the admin on remote machine and WinRM has been enabled.
Upvotes: 1
Views: 1263
Reputation: 1742
Catch error with try/catch by adding -ErrorAction Stop
and display last error with $error[0]
Try{
$result = Invoke-Command -ComputerName $servername -ErrorAction Stop -ScriptBlock {
param($appPoolName)
Get-WebAppPoolState -Name $appPoolName
} -ArgumentList $appPoolName | Select-Object value
}
Catch{
$result = $error[0]
}
Upvotes: 1
Reputation: 10044
In order to catch the error, it needs to be terminating. You can force this with -ErrorAction Stop
.
try {
$result = Invoke-Command -ComputerName $servername -ScriptBlock {
param($appPoolName)
Get-WebAppPoolState -Name $appPoolName
} -ArgumentList $appPoolName -ErrorAction Stop | select value
}
catch {
$result = [pscustomobject]@{"value"="Not Found"}
}
Upvotes: 1