Variables and Operators (add, subtract, divide...)

In PowerShell, all variable names start with the “$” character.
Creating a new variable can be done in several ways:

$MyVariable = SomeValue
$MyVariable = "Some String Value"
[DataType]$MyVariable = SomeValue
New-Item Variable:\MyVariable -value SomeValue
New-Variable:\MyVariable -value SomeValue

Variable names containing punctuation, can be handled with the syntax ${MyVari@ble} = SomeValue
However if the braces ${ } contain a colon ":" then PowerShell will treat the variable as a PATH and store the values directly in that file.
${C:\some_file.txt} = SomeValue

Operators allow you to assign a value to the variable, or perform mathematical operations:

  Operator   Description

     = n     Equals n
    += n     Increase value by n (for strings will append n to the string)
    -= n     Decrease the value by n
    *= n     Multiply the value by n (for strings, duplicate the string n times)
    /= n     Divide the value by n
    %= n     Divide the value by n and assign the remainder (modulus)

  Arithmetic operators:

    + Add, - Subtract, * Multiply, / Divide, % Mod(Remainder from a division)

 .NET Math library:

 [Math]::Abs(n)
 [Math]::Equals(objA,ObjB)
 [Math]::Exp(double)
 [Math]::Ceiling(n)
 [Math]::Floor(n)
 [Math]::Max(m,n)
 [Math]::Min(m,n)
 [Math]::Round(n)
 [Math]::Truncate(n)

 [system.math] | gm -static

PowerShell will follow normal arithmetic precedence working left to right, parentheses can be used override this.

Examples

$myPrice = 128
$myPrice += 200
$myItem = "Barbecue grill"
$myDescription = $myItem + " $ " + $myPrice

$CastAsString = "55"
$myHexValue = 0x10
$myExponentialValue = 6.5e3

Strongly typed:
[int]$myPrice = 128
[string]$myDescription = "Barbecue grill"
[string]$myDescription = 123
[string]$myDate = (get-date).ToString("yyyyMM")
$([DateTime] "12/30/2009")
$([DateTime]::Now)
[datetime]$start_date=[datetime]::now.date.addDays(-5)

When creating strongly typed variables it can be helpful to indicate the datatype in the variable name: $strProduct or $intPrice

Array variables:

$myArray = "The", "world", "is", "everlasting"

PowerShell can also assign values to multiple variables:

$varX, $varY = 64
$varA, $varB, $varC = 1, 2, 3

That will assign 1 to $varA, 2 to $varB, and 3 to $varC.

Script blocks

An entire script block can be stored in a variable: $myVar = { a bunch of commands }
Then run/call the script using &
PS C:\> & $myVar

You may want to take this a step further and turn the script block into a Function or Filter.

Concatenating strings (appending text)

The += operator can be used to add one string to another

$text = "Hello"
$text += "world"
$text

An alternative concatenation method is to use a StringBuilder .Net object, this has the advantage of being much faster which may be important when working with long strings or repeatedly in a loop.

$stringbuilder = New-Object -TypeName System.Text.StringBuilder
$null = $stringbuilder.Append("Hello")
$null = $stringbuilder.Append("World")
$stringbuilder.ToString()

Reserved Words - the following may not be used as identifiers (unless surrounded in quotes)
break, continue, do, else, elseif, for, foreach, function, filter, in, if, return, switch, until, where, while.

“Most variables can show either an upward trend or a downward trend, depending on the base year chosen” ~ Thomas Sowell

Related:

PowerShell Operators - More advanced Operators for Arrays and formatting expressions.
Reference variables - Change the value of a passed variable
Automatic variables - Variables are created and maintained by PowerShell $_, $Args, $Error, $Home etc
Set-PSBreakpoint - Set a breakpoint on a line, command, or variable
Get-Item Variable:
Clear-Variable - Remove the value from a variable
Get-Variable - Get a PowerShell variable
New-Variable - Create a new variable
Remove-Variable - Remove a variable and its value
Set-Variable - Set a variable and a value


© Copyright SS64.com 1999-2014
Some rights reserved