$error variable behaves differently in generated executable
norrisgc opened this issue · 4 comments
Trying to adapt an existing large PowerShell script application to work with PS2EXE, I've run into a number of problems, mainly due to the application not accepting normal (for PowerShell) parameters which become mangled when using PS2EXE. I've overcome all the problems except one.
This application extensively uses a local $error variable. While this works normally, once the .ps1 file is turned into a .exe using PS2EXE, the $error variable becomes unchangable (ERROR: Cannot overwrite variable Error because it is read-only or constant or A variable with name 'Error' already exists.) I can't find anything which would change the behaviour of $error when using PS2EXE.
Hello norrisgc,
did I read right, you're trying to change the $ERROR automatic variable by overwriting? Never do that, you don't know what the effect is. The automatic variable $ERROR is Read-Only!
It works in your script because you're not really overwriting the automatic variable $ERROR but the variable $SCRIPT:ERROR which is a local variable in your script with the same name as the automatic variable. When compiling your script with PS2EXE, your script is no longer a script and now you try to change $GLOBAL:ERROR. $GLOBAL:ERROR is Read-Only.
Please use another variable name instead of ERROR.
Greetings
Markus
$error is normally global, public and constant. That is, constant, not read-only.
Without $PS2EXE, there is normally no script or local $error variable. A local or script $error variable can therefore we used because it is not constant or read-only. This does not in any way affect the global $error variable: that remains invariant (apart from things like Write-Error which can change it regardless.)
With PS2EXE, there are $error variables at all three scopes, and all are constant. Therefore none of those can be changed or removed, and that breaks anything which tries to use a local or script $error variable.
$error has other strange behaviour using PS2EXE: for example, you can't pipe it to Get-Member; it results in "You must specify an object for the Get-Member cmdlet."
Hello norrisgc,
with PS2EXE you have no script and no function, so there is no script scope and no local scope! There is only the global scope as if you were executing interactively, and there $ERROR is read-only.
$ERROR has no strange behaviour in PSEXE: As long as there has been no error, $ERROR is $NULL and when you try to pipe a null value to Get-Member, Get-Member returns "You must specify an object for the Get-Member cmdlet.".
Greetings
Markus
Closed since no response for about 3 weeks