Why isn’t my PowerShell retry function executing the script block?

0
0
Asked By MellowPine47 On

I'm new to PowerShell and am trying to write a retry function that accepts a script block, the number of attempts, a delay between attempts, and an operation name. The function should execute the supplied operation, log each attempt, retry after failures, and throw an error if all attempts fail. However, none of the logging inside the retry function appears, even when I pass a simple test script block that only writes "INSIDE RETRY." The function is called with a script block such as `$StopServiceOperation = { param($names) Stop-Relevant-Services -serviceNames $names }`, followed by `Retry-Operation -functionName $StopServiceOperation -retryAttempts 3 -waitTimeBetweenAttempts 30 -operationName "Stop Services"`. What could prevent the function body from running?

2 Answers

Answered By QuietOrbit9 On

The problem was an extra pair of curly braces around the function body. The opening brace after the `param(...)` declaration started a separate script block, so PowerShell only initialized the parameters and then stopped instead of executing the retry logic. Removing that stray `{` and its matching `}` allows the function body to run normally.

MellowPine47 -

That was exactly it. I had been staring at the code for too long and completely missed the extra script block. Removing the stray braces fixed the function.

Answered By SilverMaple22 On

For troubleshooting issues like this, it helps to format the script in an editor with PowerShell support. Syntax highlighting, bracket matching, and automatic formatting can make an accidental extra script block much easier to spot. Also, splatting can make calls with several parameters cleaner than using backticks for line continuation.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.