Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string is null or empty in PowerShell?

Is there a built-in IsNullOrEmpty-like function in order to check if a string is null or empty, in PowerShell?

I could not find it so far and if there is a built-in way, I do not want to write a function for this.

like image 271
pencilCake Avatar asked Dec 06 '12 07:12

pencilCake


People also ask

How do you check if a string is null or empty?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

How do you check if an object is empty or null in PowerShell?

Type-check with the -is operator returns false for any null value. In most cases, if not all, $value -is [System. Object] will be true for any possible non-null value.

How do you check if a string is an empty string?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

Is variable null PowerShell?

A variable is NULL until you assign a value or an object to it. This can be important because there are some commands that require a value and generate errors if the value is NULL.


1 Answers

You guys are making this too hard. PowerShell handles this quite elegantly e.g.:

> $str1 = $null > if ($str1) { 'not empty' } else { 'empty' } empty  > $str2 = '' > if ($str2) { 'not empty' } else { 'empty' } empty  > $str3 = ' ' > if ($str3) { 'not empty' } else { 'empty' } not empty  > $str4 = 'asdf' > if ($str4) { 'not empty' } else { 'empty' } not empty  > if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' } one or both empty  > if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' } neither empty 
like image 152
Keith Hill Avatar answered Oct 12 '22 05:10

Keith Hill