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

It’s very easy and straightforward to check if the string is null or empty in C# and Java. However, in the PowerShell, it is slightly tricky as it does not hold null. So How to check if a string is null or empty in PowerShell?

There are 2 best ways to verify if the string is null or empty and let’s look at both the approach with examples.

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

One thing we should know about PowerShell is the null will be converted to empty strings. So even if you pass any null value to commandlet or functions it will be converted to empty string.

Using IsNullOrEmpty Static Method

PowerShell comes up with a built-in static method named IsNullOrEmpty which could be used to verify the null or empty check.

Syntax:

Example of IsNullOrEmpty in PowerShell

The above code returns true which mean the string is empty.

Using conditional Statement

The second approach is to use a conditional statement to verify if the string is empty or null. Let’s take a look at the different examples and scenarios.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *