Search code examples
powershellif-statementiispowershell-remoting

PowerShell script - check for exit code


I have the following script:

foreach ($server in $ProductList.$SelectedServer) {
    Invoke-Command -ComputerName $server -Credential domain\user -ScriptBlock {
        Import-Module WebAdministration
        echo "restarting AppPool $args[0] ... on $args[1]"
        Restart-WebAppPool -Name $args[0] -ErrorAction Stop
        echo "Restarted WebApp $args[0] on $args[1]"
    }
} -ArgumentList $SelectedAppPool, $Server

I would like to check if the Restart-WebAppPool command executes successfully. If it does I echo 'it worked' else echo 'It did not work'.

The goal is to provide a simple plain english message rather than the typical unhandled exception.


Solution

  • In theory, you're most of the way there, I don't know off the top of my head under what circumstances Restart-WebAppPool throws a terminating error, but in order to do anything with them you'll need try/catch blocks:

    try {
        Restart-WebAppPool -Name $args[0] -ErrorAction stop
        Write-Host "It worked"
    } catch {
        Write-Host "It did not work"
        # Error handling goes here.
    }
    

    The "It worked" output will only be displayed if no terminating errors are thrown by Restart-WebAppPool