Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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?

like image 212
PortMan Avatar asked Mar 08 '16 23:03

PortMan


People also ask

How do you use error variables in PowerShell?

$Errorvariable has become an array now. You can get the individual output as an array typical method. To check the error capacity, you can run the below command. When the capacity of storing error reaches 4, again this variable automatically increases its capacity by 4, so the total capacity becomes 8.

How do I get errors in PowerShell?

You can use Get-Error to display a specified number of errors that have occurred in the current session using the Newest parameter. The Get-Error cmdlet also receives error objects from a collection, such as $Error , to display multiple errors from the current session.

How do you check if a variable is null in PowerShell?

$null is one of the automatic variables in PowerShell, which represents NULL. You can use the -eq parameter to check if a string variable equals $null . It returns True if the variable is equal to $null and False if the variable is not equal to $null .

What is error variable in PowerShell?

The Error variable is a collection ( ArrayList ) of handled and unhandled errors raised in the PowerShell session.


1 Answers

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
like image 127
Harald F. Avatar answered Oct 18 '22 16:10

Harald F.