Check if a string is not NULL or EMPTY

Powershell

Powershell Problem Overview


In below code, I need to check if version string is not empty then append its value to the request variable.

if ([string]::IsNullOrEmpty($version))
{
	$request += "/" + $version
}

How to check not in if condition?

Powershell Solutions


Solution 1 - Powershell

if (-not ([string]::IsNullOrEmpty($version)))
{
    $request += "/" + $version
}

You can also use ! as an alternative to -not.

Solution 2 - Powershell

You don't necessarily have to use the [string]:: prefix. This works in the same way:

if ($version)
{
    $request += "/" + $version
}

A variable that is null or empty string evaluates to false.

Solution 3 - Powershell

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
	$request += "/" + $version
}

Solution 4 - Powershell

If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:

[CmdletBinding()]
Param (
    [parameter(mandatory=$true)]
    [ValidateNotNullOrEmpty()]
	[string]$Version
)

Solution 5 - Powershell

if (!$variablename) 
{
    Write-Host "variable is null" 
}

I hope this simple answer will resolve the question. Source

Solution 6 - Powershell

I would define $Version as a string to start with

[string]$Version

and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like

while (-not($version)){
    $version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version

Solution 7 - Powershell

> You can use the [string]::IsNullOrEmpty($version) method if it is a string. > But, I was looking for a universal way to check nulls (regardless of data type) > in Powershell. Checking for null (or not null) values in > PowerShell is tricky. Using ($value -eq $null) or ($value -ne > $null) does not always work. Neither does if($value). Using them > can even cause problems later on.
> Just read this Microsoft article below (IN IT'S ENTIRETY) to get a grasp > of how tricky nulls can be in Powershell. > > [https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1][1] >
> I wrote these two functions below for checking for null (or not null) values > in PowerShell. I "believe" they should work for any and all values > and data types. > > I hope someone finds them helpful. > I am not sure why MS hasn't put something like this into PowerShell natively to > make handling nulls easier (and less dangerous) in PowerShell. > > I hope this helps someone. > > If anyone knows of an unseen "pitfall" or problem with this method, > please post a comment here so we can know that. > Thanks!

<#
*********************  
FUNCTION: ValueIsNull
*********************  
Use this function ValueIsNull below for checking for null values
rather using -eq $null or if($value) methods.  Those may not work as expected.     
See reference below for more details on $null values in PowerShell. 
[https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1][1]

An if statement with a call to ValueIsNull can be written like this:
if (ValueIsNull($TheValue))    
#>

function ValueIsNull {
  param($valueToCheck)
  # In Powershell when a parameter of a function does not have a data type defined,
  # it will create the parameter as a PSObject. It will do this for 
  # an object, an array, and a base date type (int, string, DateTime, etc.)
  # However if the value passed in is $null, then it will still be $null.
  # So, using a function to check null gives us the ability to determine if the parameter
  # is null or not by checking if the parameter is a PSObject or not.
  # This function could be written more efficiently, but intentionally 
  # putting it in a more readable format.
  # Special Note: This cannot tell the difference between a parameter
  # that is a true $null and an undeclared variable passed in as the parameter.
  # ie - If you type the variable name wrong and pass that in to this function it will see it as a null.
  
  [bool]$returnValue = $True
  [bool]$isItAnObject=$True
  [string]$ObjectToString = ""
  
  try { $ObjectToString =  $valueToCheck.PSObject.ToString() } catch { $isItAnObject = $false }

  if ($isItAnObject)
  {
    $returnValue=$False
  }

  return $returnValue
}
<# 
************************
FUNCTION: ValueIsNotNull 
************************
Use this function ValueIsNotNull below for checking values for 
being "not-null"  rather than using -ne $null or if($value) methods.
Both may not work as expected.

See notes on ValueIsNull function above for more info.

ValueIsNotNull just calls the ValueIsNull function  and then reverses
the boolean result. However, having ValueIsNotNull available allows
you to avoid having  to use -eq and\or -ne against ValueIsNull results.
You can disregard this function and just use !ValueIsNull($value). 
But, it is my preference to have both for easier readability of code.

An if statement with a call to ValueIsNotNull can be written like this:
if (ValueIsNotNull($TheValue))    
#>

function ValueIsNotNull {
  param($valueToCheck)
  [bool]$returnValue = !(ValueIsNull($valueToCheck))
  return $returnValue
}

> You can use the following list of calls to ValueIsNull to test it out.

  $psObject = New-Object PSObject
  Add-Member -InputObject $psObject -MemberType NoteProperty -Name customproperty -Value "TestObject"
  $valIsNull = ValueIsNull($psObject)

  $props = @{
    Property1 = 'one'
    Property2 = 'two'
    Property3 = 'three'
    }
  $otherPSobject = new-object psobject -Property $props
  $valIsNull = ValueIsNull($otherPSobject)
  # Now null the object
  $otherPSobject = $null
  $valIsNull = ValueIsNull($otherPSobject)
  # Now an explicit null
  $testNullValue = $null
  $valIsNull = ValueIsNull($testNullValue)
  # Now a variable that is not defined (maybe a type error in variable name)
  # This will return a true because the function can't tell the difference
  # between a null and an undeclared variable.
  $valIsNull = ValueIsNull($valueNotDefine)

  [int32]$intValueTyped = 25
  $valIsNull = ValueIsNull($intValueTyped)
  $intValueLoose = 67
  $valIsNull = ValueIsNull($intValueLoose)
  $arrayOfIntLooseType = 4,2,6,9,1
  $valIsNull = ValueIsNull($arrayOfIntLooseType)
  [int32[]]$arrayOfIntStrongType = 1500,2230,3350,4000
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  #Now take the same int array variable and null it.
  $arrayOfIntStrongType = $null
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  $stringValueLoose = "String Loose Type"
  $valIsNull = ValueIsNull($stringValueLoose)
  [string]$stringValueStrong = "String Strong Type"
  $valIsNull = ValueIsNull($stringValueStrong)
  $dateTimeArrayLooseValue = @("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime])
  $valIsNull = ValueIsNull($dateTimeArrayLooseValue)
  # Note that this has a $null in the array values.  Still returns false correctly.
  $stringArrayLooseWithNull = @("String1", "String2", $null, "String3")
  $valIsNull = ValueIsNull($stringArrayLooseWithNull)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNilesh KhisadiyaView Question on Stackoverflow
Solution 1 - PowershellMark WraggView Answer on Stackoverflow
Solution 2 - PowershellPalle DueView Answer on Stackoverflow
Solution 3 - Powershellrufer7View Answer on Stackoverflow
Solution 4 - PowershellSamselvaprabuView Answer on Stackoverflow
Solution 5 - PowershellAshuView Answer on Stackoverflow
Solution 6 - PowershellAdam WemlingerView Answer on Stackoverflow
Solution 7 - PowershellTodd AlbersView Answer on Stackoverflow