PowerShell : Operators

PowerShell supports several types of operators to help you manipulate values.

We can divide all the PowerShell operators into the following groups

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Redirection Operators
  • Split and Join Operators
  • Type Operators
  • Unary Operators

Arithmetic Operators

Arithmetic operators (+, -, *, /, %) are used to calculate values in a command or expression in the same way that they are used in algebra.

PS C:\> 2 + 3
5
PS C:\> 2 * 3
6
PS C:\> 6 - 2
4
PS C:\> 6 / 2
3
PS C:\> 6 % 2
0

Variables

PS C:\> $a = 10
PS C:\> $b = 20
PS C:\> $c = $a + $b
PS C:\> $c
30
PS C:\> $d = $a -$b
PS C:\> $d
-10

Strings, arrays, and hash tables

PS C:\> "file" + "name"
filename
PS C:\> "H.no:" + 123
H.no:123
PS C:\Users\Sree> @(1, "one") + @(2.0, "two")
1
one
2
two
PS C:\Users\Sree> @{"one" = 1} + @{"two" = 2}

Name  Value
----  -----
one   1
two   2

Dates

PS C:\Users\Sree> Get-Date

18 December 2018 08:16:29 PM

PS C:\Users\Sree> (Get-Date).AddDays(2)

20 December 2018 08:15:45 PM

PS C:\Users\Sree> (Get-Date).AddDays(-2)

16 December 2018 08:16:16 PM

Multiply strings and arrays

PS C:\> "ab" * 3
ababab

PS C:\> @("!") * 4
!
!
!
!

Assignment Operators

Assignment Operators (=, +=, -=, *=, /=, %=) are used to assign, change, or append values to variables. You can combine arithmetic operators with an assignment to assign the result of the arithmetic operation to a variable.

PS C:\> $var = "Hello"
PS C:\> $range = [2..8]
PS C:\> $hash = @{ "one"=1; "two"=2}
PS C:\Users\Sree> $var = 10
PS C:\Users\Sree> $var += $var
PS C:\Users\Sree> $var
20
PS C:\Users\Sree> $abc = 15
PS C:\Users\Sree> $abc -= $abc
PS C:\Users\Sree> $abc
0

Comparison Operators

Comparison operators (-eq, -ne, -gt, -lt, -le, -ge) are used to compare values and test conditions.

Equality Type:

-eq equals
-ne not equals
-gt greater than
-ge greater than or equal
-lt less than
-le less than or equal

PS C:\> $spent = 1000
PS C:\> $return = 1500
PS C:\> $spent -eq $return
False
PS C:\> $spent -ne $return
True
PS C:\> $spent -gt $return
False
PS C:\> $spent -ge $return
False
PS C:\> $spent -lt $return
True
PS C:\> $spent -le $return
True
PS C:\> $message = "Hello"
PS C:\> $message -eq "Hello"
True
PS C:\> $message -eq "hello"
True
PS C:\>

Matching Type :

-like Returns true when string matches the wildcard pattern
-notlike Returns true when the string does not match the wildcard pattern
-match Returns true when string matches regex pattern; $matches contains matching strings
-notmatch Returns true when the string does not match regex pattern; $matches contains matching strings

PS> "PowerShell" -like "*shell"
True

PS> "PowerShell", "Server" -like "*shell"
PowerShell
PS> "PowerShell" -notlike "*shell"
False

PS> "PowerShell", "Server" -notlike "*shell"
Server

If -match operator returns a Boolean value then it returns that match. If -match operator return matching members, $matches doesn’t populate.

PS> "Sunday", "Monday", "Tuesday" -match "sun"
Sunday

PS> $matches
PS>
PS> "Sunday" -match "sun"
True

PS> $matches

Name Value
---- -----
0    Sun
PS> "Sunday" -notmatch "rain"
True

PS> $matches
PS>
PS> "Sunday" -notmatch "day"
False

PS> $matches

Name Value
---- -----
0 day
PS> "Sunday" -notmatch "sun"
False

PS> $matches
Name Value
---- -----
0 sun

PS> "Sunday", "Monday" -notmatch "sun"
Monday

Logical Operators

Logical operators (-and, -or, -xor, -not, !) are used to connect conditional statements into a single complex conditional.

-and Logical AND. TRUE when both statements are TRUE.
-or Logical OR. TRUE when either statement is TRUE
-xor Logical EXCLUSIVE OR. TRUE when only one statement is TRUE
-not Logical not. Negates the statement that follows.
! Same as -not

PS C:\> $a = 20
PS C:\> $b = 25
PS C:\> ($a -lt $b) -and ( $a -eq 22)
False
PS C:\> ($a -lt $b) -and ( $a -ne 22)
True
PS C:\> ($a -lt $b) -or ( $a -eq 22)
True
PS C:\> ($a -lt $b)
True
PS C:\> !($a -lt $b)
False
PS C:\> -not ($a -lt $b)
False

Redirection Operators

Redirection operators (>, >>, 2>, 2>>, and 2>&1) are used to send the output of a command or expression to a text file.

> Send specified stream to a file.
>> Append specified stream to a file.

1 – Success Stream
2 – Error Stream
3 – Warning Stream
4 – Verbose Stream
5 – Debug Stream
6 – Information Stream
* – All Streams

PS C:\> Get-ChildItem > items.txt
PS C:\> Get-Content items.txt

Send all Success stream data to a file.

.\script.ps1 > script.log

Send Success, Warning, and Error streams to a file.

.\script.ps1 3>&1 2>&1 > script.log

3>&1 redirects the Warning stream to the Success stream

2>&1 redirects the Error stream to the Success stream

> redirects the Success stream

Redirect all streams to a file

.\script.ps1 *> script.log

Suppress all Write-Host and Information stream data

.\script.ps1 6>$null > script.log

Append stream to an existed file

.\script.ps1 6>$null >> script.log

Split and Join Operators

The -split and -join operators divide and combine substrings. The -split operator splits a string into substrings. The -join operator concatenates multiple strings into a single string.

PS C:\> -split "Hello World"
Hello
World

The default delimiter is whitespace, including spaces and non-printable characters, such as newline (n) and tab (t).

Split with delimiter 

PS C:\> "Lastname:FirstName:Address" -split ":"
Lastname
FirstName
Address

To preserve the delimiter, enclose in parentheses.

PS C:\Users\Sree> “Lastname:FirstName:Address” -split “(:)”
Lastname
:
FirstName
:
Address

To preserve the part of delimiter, enclose the part that you want to preserve.

PS C:\Users\Sree> "Lastname/:/FirstName/:/Address" -split "/(:)/"
Lastname
:
FirstName
:
Address

Specify a maximum number of times that a string has to split

PS C:\> "AB,BC,CD,DE" -split "," ,3
AB
BC
CD,DE

Split the string at multiple delimiters

PS C:\> "Lastname-FirstName:Address" -split'[-:]'
Lastname
FirstName
Address

Join strings

PS C:\> -join ("Windows", "PowerShell", "5.0")
WindowsPowerShell5.0

Joins strings delimited by a space

PS C:\> ("Windows", "PowerShell", "5.0") -join " "
Windows PowerShell 5.0

The following statements use a multiple-character delimiter to join three strings:

PS C:\> $a = "WIND", "S P", "ERSHELL"
PS C:\> $a -join "OW"
WINDOWS POWERSHELL

Type Operators

Type operators (-is, -isnot, -as) are used to find or change the .NET Framework type of an object.

-is Returns TRUE when the input is an instance of the specified .NET type.
-isNot Returns TRUE when the input not an instance of the specified.NET type.
-as Converts the input to the specified .NET type.

PS> 10 -is "int"
True
PS> 10 -isNot [Float]
True
PS> (get-date) -is [DateTime]
True
PS> "18/12/2018" -is [DateTime]
False
PS> "18/12/2018" -is [String]
True
PS> (get-process PowerShell)[0] -is [System.Diagnostics.Process]
True
PS C:\> $date -as [DateTime]

18 December 2018 12:00:00 AM

Unary Operators

Unary operators are used to incrementing or decrementing variables or object properties and to set integers to positive or negative numbers.

PS C:\> $a =5
PS C:\> $a++
PS C:\> $a
6
PS C:\> $a--
PS C:\> $a
5

Special Operators

Call operator &

It is also known as the “invocation operator”, used to run commands that are stored in variables and represented by strings or script blocks. The call operator executes in a child scope.

PS C:\> $c = "get-executionpolicy" 
PS C:\> $c get-executionpolicy 
PS C:\> & $c 
AllSigned

Ampersand background operator

It acts similarly to the UNIX “ampersand operator” which runs the command as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job.

PS C:\> Get-Process -Name pwsh &

Cast operator [ ]

It is used to converts or limits objects to the specified type. If the objects cannot be converted, PowerShell generates an error.

PS C:\> [int64]$a = 50

Dot sourcing operator

Runs a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope.

PS C:\> . c:\users\sample.ps1
PS C:\> . .\sample.ps1

Pipeline operator |

Sends (“pipes”) the output of the command that precedes it to the command that follows it. When the output includes more than one object (a “collection”), the pipeline operator sends the objects one at a time.

PS C:\> Get-Process | Get-Member

Property dereferences operator .

Accesses the properties and methods of an object.

PS C:\> (get-host).version
Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      17134  407

PS C:\> (Get-Process PowerShell).kill()

 

Advertisements

Learn Technology

%d bloggers like this: