I’m building a retry function that accepts a scriptblock and some retry settings, but the function seems to stop before running its body. What should I check?
Why does my PowerShell retry function stop before it runs the scriptblock?
Answers
Check the braces around the function. The parameter declaration already sits inside the function’s scriptblock, so an extra opening brace immediately after param(...) starts a separate nested scriptblock. The function can then finish after setting up its parameters instead of reaching the retry loop. Remove that extra brace and its matching closing brace.
Reply to this answer
This is exactly the kind of bug that gets hard to see after staring at the same code for hours. Run a formatter and check the indentation and brace matching. The function should have one outer body, with the loop and try/catch blocks nested inside it, not another block opened after the parameters.
Reply to this answer
The call operator with a scriptblock parameter is a reasonable way to invoke the supplied operation. Since the function body itself wasn’t being reached, I’d fix the block structure before changing how the scriptblock is passed. A tiny test that writes a marker from inside the retry function can confirm the body is running.
Reply to this answer
Add your answer
Answers are reviewed before publication.
saffronfax:
That was the problem. The extra brace made the rest of the function a separate scriptblock, so the retry code never ran.