Variables

Learn all about variables in PowerShell.


In this video, we go over the basics of variables in PowerShell.

You can find the code for this video below.

$Variable = "Nice!"
$Variable 
$Variable | Get-Member
$Variable.Length

${my weird-variable!} = "Test"
${my weird-variable!}

Get-Variable

Get-Variable -Name Variable 
Get-Variable -Name Variable -ValueOnly

Set-Variable -Name 'Test' -Value "Cool" -Scope Global -Description "Nice" -Option ReadOnly 
Get-Variable -Name Test | Format-List * 
$Test 
Clear-Variable -Name 'Test'
Remove-Variable -Name 'Test'
Remove-Variable -Name 'Test' -Force
$Test -eq $null

[int]$MyNumber = "123"
[int]$MyNumber = "NotANumber"
[DateTime]$MyDate = (Get-Date)
$MyDate = 10

Push-Location Variable:\
Get-ChildItem
New-Item -Path Variable:\ -Name 'MyPathVariable' -Value "Nice" -Force
$MyPathVariable
Pop-Location

$Global:GlobalVar = 123
$Script:ScriptVar = 123
$Local:LocalVar = 123

function Scope1 {
    $Variable = 123
    $Variable 
}

Write-Host "-----"
$Variable = 234
Scope1
$Variable

function Scope1 {
    Set-Variable -Name 'Variable' -Value 123 -Scope 1
    $Variable
}

Write-Host "-----"
$Variable = 234
Scope1
$Variable

Import-Module .\module.psm1 -Force
Write-Host "-----"
$Variable = 234
Scope2
$Variable
$Global:GlobalVar
Scope3

module.psm1

function Scope2 {
    Set-Variable -Name 'Variable' -Value 123 -Scope 1
    $Variable
    $Global:GlobalVar = "FromModule"
    $Script:ScriptVar = "FromScope2"
}

function Scope3 {
    $Script:ScriptVar
}