Variables and Types

Variables

Basic

Variables are defined by prefixing them with $.
In PowerShell, it is not case sensitive.

PS> $a = 1
PS> $a
1
PS> $A
1

You can save the results of commandlets, methods, etc. as objects.

PS> $date = Get-Date
PS> $date.Year
2018

When including special characters

To include special characters (-, (, ), . , :etc.), use ${}.

PS> ${test-test} = "test"

Items in the PSDrive can be treated as variables.

# Example: Targeting an item (script.ps1) in the FileSystem provider
PS C:\Users\user\Desktop> ${C:\Users\user\Desktop\script.ps1}
Write-Host "Hello!"
PS C:\Users\user\Desktop> .\script.ps1
Hello!

Types

About types

Both fully qualified names and aliases can be used.

PS> [System.Int32]$a = 1 # Fully qualified name
PS> [int]$a = 1          # Aliase

How to check the type

  • Use Get-Member
  • Use the GetType method
PS> $a = 1
PS> $a | Get-Member
 
   TypeName: System.Int32
Abbreviation
 
PS> $a.GetType().FullName
System.Int32

Type Checking

PS> $a -is [int]
True
PS> $a -isnot [int]
False

Type Conversion

Explicit type conversion ( cast )

There are multiple methods.

  • $variable = [type] cast-target
    For impossible cast: Error.
  • $variable = cast-target -as [type]
    For impossible cast: Does not result in an error, returns Null

If you want to cast a variable, you need to know that $variable = [type] cast-target.
It will give you an error.

# $variable = [type] cast-target
PS> $date = [datetime]"2018/05/16"
PS> $date.Date
 
2018516 0:00:00
 
PS> $date.Day
16

# $variable = cast-target -as [type]  
PS> $date = "2018/05/16" -as [datetime]
PS> $date.DayOfWeek
Wednesday
PS> $date = "a" -as [datetime] # impossible cast
PS> $date
PS>

Implicit Type Conversion

The type of the right side is converted to match the type of the left side.

PS> $a = 1
PS> $b = "1"
PS> $a + $b  # $b is converted to [int].
2
PS> $b + $a  # $a is converted to [string].
11

YouTube

Click here for a video explanation.

About Variables | Microsoft Docs

Last modified October 11, 2022: update (8216439)