When is an Error not an Error?
Working with PowerShell can be a bit tricky, and can often require you to have a bit of understanding about how it works. For example, consider these two scenarios:
April 20, 2011
Working with PowerShell can be a bit tricky, and can often require you to have a bit of understanding about how it works. For example, consider these two scenarios:
# onetry { 1 / 0 } catch { write-host 'oops' }# two$zero = 0try { 1 / $zero } catch { write-host 'oops' }
With the first scenario, you'll never actually get your "oops" output. That's because PowerShell never actually executes the illegal divide by zero operation. Instead, it's caught by the parser as it's translating your command into behind-the-scenes executable code. It sees the illegal operation coming and barfs without actually trying it. In the second instance, however, the parser can't see the fail coming because we've put zero into a variable. The parser doesn't look inside variables; because it doesn't see the illegal literal string "/0," it lets the operation proceed to execution - meaning you get an error you can actually catch.
This kinda thing can be really confusing, and it's one of those "gotchas" you just have to pick up from experience. But now you know.
About the Author
You May Also Like