Category:Variables (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 { }
in order to delimit them, eg ${varname}
.
PowerShell is all about manipulating objects, and all variables are objects. When you assign a value to a new variable, the type of object that it is (string, integer, etc) is automatically defined. Which is normally useful as you don't have to worry about what type of object/variable you want to create, PowerShell will work it out for you. However sometimes you need to force a variable to contain a specific data type to avoid errors or other problems down the line. Using a prefix of [type]
achieves this...
[string]$result = $PingResult.Status
Data types
Notation | Data Type |
---|---|
[adsi] |
Active Directory Services object |
[array] |
Array (see Arrays) |
[bool] |
True / false (can also be [boolean] )
|
[byte] |
8-bit unsigned character |
[char] |
Single character |
[datetime] |
Date and time (see Datetime) |
[decimal] |
128-bit decimal |
[double] |
Double-precision 64-bit floating point number |
[int] |
32-bit integer |
[long] |
64-bit integer |
[single] |
Single-precision 32-bit floating point number |
[string] |
String of characters (see Strings) |
[timespan] |
Duration of time |
[wmi] |
Windows Management Instrumentation (WMI) instance or collection |
[wmiclass] |
WMI class |
[xml] |
XML object |
Variable Information
As PowerShell object (variables) tend to be black boxes that can contain anything or nothing, its often necessary to understand more about one. All objects contain Properties and Methods.
- Properties
- Are containers for data
- Methods
- Are in-built functions that allow an object to be manipulated.
Variable Type
To see the object type of a variable...
PS E:\> $var.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
Variable Properties
Simple objects such as strings will contain only one property but complicated can contain many more, and even further objects. If you pipe an object through Format-List
you get a fuller picture...
PS E:\> Get-WMIObject Win32_BIOS
SMBIOSBIOSVersion : 786F3 v01.16
Manufacturer : Hewlett-Packard
Name : Default System BIOS
SerialNumber : CPC123456J
Version : HPQOEM - 20090219
PS E:\> Get-WMIObject Win32_BIOS | Format-List *
Status : OK
Name : Default System BIOS
Caption : Default System BIOS
SMBIOSPresent : True
....TRUNCATED TO SAVE SPACE !!....
SMBIOSBIOSVersion : 786F3 v01.16
SMBIOSMajorVersion : 2
SMBIOSMinorVersion : 6
SoftwareElementID : Default System BIOS
SoftwareElementState : 3
TargetOperatingSystem : 0
Version : HPQOEM - 20090219
Scope : System.Management.ManagementScope
Path : \\LAPTOP1\root\cimv2:Win32_BIOS.Name="Default System BIOS",SoftwareElementID="Default System BI
OS",SoftwareElementState=3,TargetOperatingSystem=0,Version="HPQOEM - 20090219"
Options : System.Management.ObjectGetOptions
ClassPath : \\LAPTOP1\root\cimv2:Win32_BIOS
Properties : {BiosCharacteristics, BIOSVersion, BuildNumber, Caption...}
SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers : {dynamic, Locale, provider, UUID}
Site :
Container :
Variable Properties and Methods
PS E:\ > $string | get-Member
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Clone Method System.Object Clone()
CompareTo Method int CompareTo(System.Object value), int CompareTo(string strB)
Contains Method bool Contains(string value)
CopyTo Method System.Void CopyTo(int sourceIndex, char[] destination, int destinationIndex,...
EndsWith Method bool EndsWith(string value), bool EndsWith(string value, System.StringCompari...
Equals Method bool Equals(System.Object obj), bool Equals(string value), bool Equals(string...
GetEnumerator Method System.CharEnumerator GetEnumerator()
....TRUNCATED TO SAVE SPACE !!....
ToString Method string ToString(), string ToString(System.IFormatProvider provider)
ToUpper Method string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
ToUpperInvariant Method string ToUpperInvariant()
Trim Method string Trim(Params char[] trimChars), string Trim()
TrimEnd Method string TrimEnd(Params char[] trimChars)
TrimStart Method string TrimStart(Params char[] trimChars)
Chars ParameterizedProperty char Chars(int index) {get;}
Length Property System.Int32 Length {get;}
It's not uncommon for objects provided by API's to provide methods that are in fact objects themselves, you can end up with a lot of information being available once you're capable of drilling into them.
NULL
Checking whether a variable is NULL or not can be problematic. In that the easiest test doesn't always work.
Basic test for whether a variable exists or not, works in most cases...
if (!$var) {
"Variable is null"
}
If you expect your variable to be NULL or contain a positive number...
if ($var -gt 0) {
"Variable is NOT null"
}
Last resort test...
if ($var.gettype().ToString() -eq "System.DBNull") {
"Variable is null"
}
Scope
Variables only fully exist within the scope of the script or function within which they are defined. Within functions local copies of a variable are available, but manipulating them has no effect on the real/master variable in the main scope, to get around this you can use script
to enforce using the variable that's in the main script's scope...
function Local-Add($text) {
$List += $text
}
function Global-Add($text) {
$script:List += $text
}
$List = @()
$List += "Text message ONE"
$List.Length # List contains one entry
Local-Add "Text message TWO"
$List.Length # List still contains one entry
Global-Add "Text message THREE"
$List.Length # List now contains two entries
Similarly, you can create a variable within a function that has global scope...
function Create-Var {
if (!$TestVar) {
$script:TestVar = "stuff"
Write-Host 'Created $TestVar'
} else {
Write-Host '$TestVar already exists'
}
}
Create-Var
Create-Var
Write-Host '$TestVar contains [' $TestVar ']'
...which when run produces the following output...
Created $TestVar $TestVar already exists $TestVar contains [ stuff ]
You can achieve the same result by using the Set-Variable
CmdLet with the -Scope
parameter instead of script
, for example...
function Create-Var {
if (!$TestVar) {
#$script:TestVar = "stuff"
Set-Variable -Name TestVar -Value "stuff" -Scope 1
Write-Host 'Created $TestVar'
} else {
Write-Host '$TestVar already exists'
}
}
Create-Var
Create-Var
Write-Host '$TestVar contains [' $TestVar ']'
Macros / Built-in Variables
Variable | Description |
---|---|
$_ |
Variable passed through pipeline from previous command |
$? |
Success/failure of previous statement - see Basic_Error_Handler |
$Error |
Last error - array of recent errors - see $error |
$LastExitCode |
Exit code of the last natively run application |
$foreach |
Enumerator in a foreach loop |
$Host |
Information about the machine being executed on (can also use Get-Host
|
$args |
Array of arguments passed to a script - see Script_Arguments |
Environment Variable
Environmental variables can be accessed via $env
$env:userprofile # User profile (eg C:\Users\joeblogs)
dir env: # Show all available variables
For a full list use...
Get-ChildItem env:
...or for some commonly used ones...
Variable | Description | Example data |
---|---|---|
APPDATA | Application data path | C:\Users\RodHull\AppData\Roaming |
COMPUTERNAME | Local System's hostname | LAPTOP-01 |
LOGONSERVER | Domain Controller Logged into | DC-SERVER-03 |
PROCESSOR_ARCHITECTURE | CPU Architecture | AMD64 |
USERDOMAIN | Logged in user's domain | DOMAIN.COM |
USERNAME | Local System's hostname | rodhull |
Pages in category 'Variables (PowerShell)'
The following 3 pages are in this category, out of 3 total.