Difference between revisions of "Power Shell"

From vwiki
Jump to navigation Jump to search
m (→‎Variables: Added interpolation)
m (Typo fix)
 
(101 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Variables ==
#REDIRECT [[:Category:PowerShell]]
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 <code> { } </code> in order to delimit them, eg <code>${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...
<source lang="powershell"> [string]$result = $PingResult.Status </source>
 
{|cellpadding="1" cellspacing="0" border="1"
|- style="background-color:#bbddff;"
! Notation                      !! Data Type
|-
|<code> [bool] </code>  || True / false
|-
|<code> [single] </code> || Single-precision 32-bit floating point number
|-
|<code> [double] </code> || Double-precision 64-bit floating point number
|-
|<code> [byte] </code> || 8-bit unsigned character
|-
|<code> [int] </code> || 32-bit integer
|-
|<code> [long] </code> || 64-bit integer
|-
|<code> [decimal] </code> || 128-bit decimal
|-
|<code> [char]  </code> || Single character
|-
|<code> [string] </code> || String of characters
|-
|<code> [datetime] </code>      || Date or time
|-
|<code> [xml] </code> || XML object
|-
|<code> [array] </code> || Array
|-
|<code> [wmi] </code> || Windows Management Instrumentation (WMI) instance or collection
|-
|<code> [wmiclass] </code> || WMI class
|-
|<code> [adsi] </code> || Active Directory Services object
|-
|<code> [Boolean] </code> || True or False value
|}
 
 
=== Strings ===
'''Concatenation +'''
<source lang="powershell">
$strAB = $strA + $strB
</source>
 
'''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...
<source lang="powershell">
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
</source>

Latest revision as of 15:37, 4 October 2016