If Statement in Windows PowerShell

All of us should come across the need of If check when we create a powershell script. The If condition might be needed for different cases, i.e, to compare two integer values, compare string values, check a string value contains another string values. etc…In this article, I am going to write different IF condition statements.

If check with Integer value

$a = 10

If($a -eq 10)  { '$a equals 10' 
} else { '$a not equals 10' }

If with Not Equal check:

$a = 10
If($a -ne 11)  { '$a not equals 10' }

If check with String value

$str = 'Hello World'

# case insensitive check: This if check ignore the case sensitive.

If($str -eq 'hello world')  { 'True' 
} else { 'False' }

By default, all comparison operators are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a “c”.

$str = 'Hello World'

# case sensitive check: This if statement checks with case sensitive.

If($str -ceq 'hello World')  { 'True' 
} else { 'False' }

If with Not Equal check:

$str = 'Hello World'

If($str -ne 'hello worlddd')  { 'True' }

If with contains (or like ) check:

$str = 'Hello World'

If($str -like '*hello*')  { 'True'
} else { 'False' }

If with not contains (or not like ) check:

$str = 'Hello World'

If($str -notlike '*helloddd*') { 'True' 
} else { 'False' }
Advertisement

Leave a Comment