powershellvariables

How to powershell to give warning or error when using an undefined variable?


In a powershell script, if I try to use an undefined variable, it continues on its way, not indicating by any warning or error that I did so.

For example, the following script

echo "a"
echo $nonexistent_variable
echo "c"

gives the output

a
c

Is there any way to get powerShell to let me know that the variable I'm trying to use is undefined?


Solution

  • You could consider using the strict mode:

    Set-strictmode -version latest
    

    This will give you warning and errors if you do common mistakes (such as using an undeclared variable etc).

    You could also use PSDebug -Strict

    Set-PSDebug -Strict