Power Shell

From vwiki
Revision as of 12:22, 22 January 2010 by Sstrutt (talk | contribs) (→‎Variables: Added interpolation)
Jump to navigation Jump to search

Variables

All variable names are prefixed with a $, and are case insensitive (though there's no reason to not use CamelBack notation if that floats your boat).

Apart from a few reserved words and characters there's little restriction on what can be used, though note that this flexibility can cause the occasional issue, whereby PowerShell gets confused as to where a variable name finishes. Variable names can be enclosed in { } in order to delimit them, eg ${varname}</scode>.

PowerShell is all about manipulating objects, and its variables are all essentially the same, not being specifically defined as an object, string, integer, etc. Which is normally useful, however sometimes you need to force a variable to contain a data type. Using a prefix of [type] achieves this...

 [string]$result = $PingResult.Status
Notation Data Type
[bool] True / false
[single] Single-precision 32-bit floating point number
[double] Double-precision 64-bit floating point number
[byte] 8-bit unsigned character
[int] 32-bit integer
[long] 64-bit integer
[decimal] 128-bit decimal
[char] Single character
[string] String of characters
[datetime] Date or time
[xml] XML object
[array] Array
[wmi] Windows Management Instrumentation (WMI) instance or collection
[wmiclass] WMI class
[adsi] Active Directory Services object
[Boolean] True or False value


Strings

Concatenation +

$strAB = $strA + $strB

Interpolation

Interpolation allows variables to be embedded into a string and to be resolved into their actual values. This works between double quotes, but not between single quotes...

PS E:\> $sub = "replaced"
PS E:\> Write-Output "Variable has been $sub"
Variable has been replaced
PS E:\> Write-Output 'Variable has been $sub'
Variable has been $sub