Variables and Operators - PowerShell
Variables and Operators - PowerShell
$MyVariable = SomeValue
[DataType]$MyVariable = SomeValue
Multiple variables can be initialised in a single line, this will create var1 and var2:
$var2=($var1=1)+1
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
Arithmetic operators:
The .NET Math library adds more options such as Round(), Ceiling(), Max(), Min() etc
PowerShell will follow normal arithmetic precedence working left to right, parentheses can be used override this.
Examples
$myPrice = 128
$myPrice += 200
$CastAsString = "55"
$myHexValue = 0x10
$myExponentialValue = 6.5e3
Strongly typed
Forcing the correct Data Type
can prevent/trap errors in later calculations.
[int]$myPrice = 128
[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
Validation
In PowerShell V3.0, you can specify a range of valid attributes for any variable:
PS C:\> $x = 11
The variable cannot be validated because the value 11 is not a valid value for the x variable.
At line:1 char:1 + $x = 11
Array variables:
$myArray = "The", "world", "is", "everlasting"
$varX, $varY = 64
Script blocks
An entire script block can be stored in a variable: $myVar = { a bunch of commands }
You can take this one step further and turn the script block into a Function or Filter.
Reserved Words
The following may not be used as variable 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
How-to: Automatic variables - Variables created and maintained by PowerShell $_, $Args, $Error, $Home etc.
How-to: PowerShell Operators - Advanced Operators for Arrays and formatting expressions.
Get-Item Variable: