如何在使用未定义变量时使用powershell来发出警告或错误?

Por*_*Man 6 powershell

在powershell脚本中,如果我尝试使用未定义的变量,它会继续运行,而不是通过我所做的任何警告或错误来指示.

例如,以下脚本

echo "a"
echo $nonexistant_variable
echo "c"
Run Code Online (Sandbox Code Playgroud)

给出输出

a
c
Run Code Online (Sandbox Code Playgroud)

有没有办法让powerShell让我知道我试图使用的变量是未定义的?

Har*_* F. 6

您可以考虑使用严格模式:

Set-strictmode -version latest
Run Code Online (Sandbox Code Playgroud)

如果您遇到常见错误(例如使用未声明的变量等),这将为您提供警告和错误.

您也可以使用PSDebug -Strict

Set-PSDebug -Strict
Run Code Online (Sandbox Code Playgroud)