How Do You Use Conditional Logic on PowerShell Variables To Test If They Are Empty When The Variable’s Value Can Span Two Or More Lines?

Problem scenario:  Sometimes variables get values you do not expect.  Handling these exceptions is the mark of a good programmer.  

A PowerShell variable (e.g., $contint) may have the following content:
"

second line
third line"

When a variable's value can span lines, conditional tests act unpredictably when they use such a variable.  For example a conditional test of the variable like this if(!($contint)) may not work as you expect.  You may have also tried different tests like these: if($contint = "")if($contint == ""), or if(!(Get-Variable $contint)).  Those will not seem to work if you have a multi-line variable with a blank line.

How do you test if the variable is empty while taking into account the variable's value itself spans two or more lines with a top line that is blank? 

Answer
Use this:  if($contint -eq "")

This will resolve to "true" if the variable is empty.  It will evaluate to "false" if the top line in the $contint variable is blank despite other characters on lines below the first line.

Leave a comment

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