Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
10.7k views
in PowerShell by 13 13 19

What's the best way to check if the variable is not equal to null in PowerShell?

I have tried the below script

$site = Get-SPWeb -Site "http://mysite"
if($site -ne null)
{
  #MyCode
}

But I get unexpected token null in expression or statement  error

check variable not equal to null in PowerShell


2 Answers

2 like 0 dislike
by 14 18 26
selected by
 
Best answer

You are missing '$' sign before NULL, try to use $null

If($site - nq $null) { #if site variable not equal Null} 

Hope it helps

by 13 13 19
0 0
Oh shit it's my mistake, thanks for you help!
1 like 0 dislike
by 159 198 381

Check if a variable is not equal to null in PowerShell

Besides @Imran answer, I would like to share another method to check if a variable is equal or not equal to null in PowerShell

Check if a variable is not equal to null

#Metod 1 
if($variable -ne $null)
{
}

#Method 2
if($variable)
{
}

Check if a variable is equal to null

# Metod 1 
if($variable -eq $null)
{
}

#Method 2
if(!$variable)
{
}

check if variable not equal to null in PowerShell

by 13 13 19
0 0
The second method is so  simple, thank you!
If you don’t ask, the answer is always NO!
...