1

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.

2 Answers 2

1

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"}
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.