1

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.

2
  • The code you posted can't possibly work. foreach loops don't have a parameter -ArgumentList. Commented Oct 9, 2017 at 19:48
  • @AnsgarWiechers yeah had to move that up to the Invoke-Command part. Thanks for that Commented Oct 10, 2017 at 6:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Adding to this, @Joe, you might want to send a PSCredential object instead of just a Username as parameters for -Credential. Otherwise, Inside a for loop, you will have to enter the password as many times as it iterates.
Thanks @Windos. That did the trick. Just for clarification. Does the try / catch actually execute the code block in the try section ? Or does it simply try it /dry run ?
@joebegborg07 it actually executes it, but it'll stop as soon as it runs into a terminating error and jump straight to the catch block (hence you won't see "It worked" if there's an error.)

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.