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

Viewed 2007

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 $nonexistant_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?

3 Answers

While powershell does have Set-PSDebug and Set-StrictMode, fundamentally it is a bad language and is not parsing scripts properly before executing them. It will gladly ignore code that is invalid that it has not run. There is no way to validate Powershell code without executing it.

Set-PSDebug -strict
Set-StrictMode -version latest
$ErrorActionPreference = 'Stop'

if($false)
{
  Write-Output $fnord #undeclared variable
}

#powershell should halt because of an error and not get here.
write-output "this language is clownshoes"

yields

this language is clownshoes

Contrast this to parse errors, which behave reasonably:

Set-PSDebug -strict
Set-StrictMode -version latest
$ErrorActionPreference = 'Stop'

if($false)
{
  () #parseerror
}

#powershell should halt because of an error and not get here.
write-output "this text will not show"

yields

At line:9 char:4
+   () #parseerror
+    ~
An expression was expected after '('.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedExpression

So, in short, while you can have powershell error out when it attempts to read from an undeclared variable, there is no way to have powershell properly check your script for undeclared variables at parse-time.

Related