I ran into a problem I simply cannot understand. I wrote a script that uses custom Classes to handle different objects. It runs perfectly on my work machine (PowerShell 5.1) on my personal laptop (PowerShell 5.1), on every other colleague's PC, but on one of my colleague's PC (PowerShell 5.0) it does something strange. When she runs the script, it throws variable not assigned exception. The strange part? It throws it for every single $Error[0] in my script. Of course, I didn't reference to $Error[0] anywhere outside the catch part of a try-catch block, so it shouldn't exist unless there is an exception. What makes the whole thing even more strange is when the script is initiated, neither of the classes that contain a try-catch block with the $Error variable is called.
The script works on every other machine I tried, this one is the only exception. I guess it has something to do with the the PowerShell version, as every other machine has PowerShell 5.1 while hers have 5.0. Did the PowerShell prior 5.1 have this behavior? Checking the contents of an uncalled try-catch block within an uncalled Class?
The same thing happens even when I write a script that's as simple as this one:
Class Foo
{
Foo()
{
try
{
Write-Host "Bar"
}
catch
{
Write-Host $error[0]
}
}
}
Write-Host "Start program"
I don't call the class, and even if I called it, it shouldn't throw an exception, yet on that single machine, running this script throws "variable not assigned in Method" exception. On her machine, even PowerShell ISE underlines the $error variable with red, and writes the same error message. But only on her machine, it happens on neither else.
$error, and given we know the behavior doesn't occur in 5.1, I think the fair conclusion is a difference in behavior, possibly a 5.0 bug fixed in 5.1+...