Question About a Possible Mistake in PowerShell Scripting Book

0
9
Asked By CuriousCoder42 On

Hey everyone! I'm working through the PowerShell Scripting in a Month of Lunches and I have a question about Chapter 15. In the exercise's solution, the author wraps a try/catch construct inside a do/until loop. My concern is that it seems like the loop might never stop running if an exception occurs. After entering the do block, the protocol is set to 'Wsman'. In the catch block, if the protocol is default, it's changed to a fallback protocol. If the fallback has already been used, it sets the protocol to 'Stop', which is what the until condition checks for. However, right at the start of the loop, the protocol is reset to 'Wsman' again, which would overwrite the catches. Am I missing something here, or does this look like a mistake? Here's a snippet of the loop I'm referencing, focusing on the issue rather than all the params:

```powershell
ForEach ($computer in $ComputerName) {
Do {
Write-Verbose "Connect to $computer on WS-MAN"
$protocol = "Wsman"
Try {
# additional code...
} Catch {
# additional handling...
}
} Until ($protocol -eq 'Stop')
}
```

4 Answers

Answered By ScriptingSage On

I think you're onto something here! Placing the line that sets the protocol to 'Wsman' inside the do block could lead to an infinite loop if an exception occurs. It might be worth trying to move it outside the do/until structure to allow the catch block to take effect properly.

Answered By TechieTimmy On

I noticed this issue too, and it doesn't appear to be addressed in any corrections from Manning Press. It looks like it'll try 'Wsman' indefinitely! Here's a link where I raised the issue: https://github.com/psjamesp/MOL-Scripting/blob/main/15_2.ps1

CuriousCoder42 -

Glad I'm not the only one who spotted this! 😀

Answered By Bookworm_Brady On

What edition of the book are you using? Can you share the ISBN?

ScriptingSage -

I've got the digital version too; it's the 4th edition.

Answered By DevDude321 On

You're correct about how Do..Until works. It checks the until condition after each cycle of the do block. So, if it hits the catch where the protocol is set to 'Stop', it should stop the loop on the next evaluation. But as you pointed out, because the protocol resets to 'Wsman' at the beginning, it essentially negates the intended outcome.

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.