Author : MD TAREQ HASSAN | Updated : 2023/03/16

Declaring variable

# format: [<data type>] $<variable name> = <initial value>

# User defined variable
[int] $count = 0
[string] $message = "Hey there!"

# Automatic variable: $PSVersionTable.PSVersion, $true, $false, $Error
Write-Host $PSVersionTable.PSVersion

Details: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_variables

Data types

PowerShell core is based on .Net framework, therefore .Net types are available to PowerShell Core.

Value types:

Reference types:

To get type of a variable: .GetType()

# Integer
[int] $count = 0
Write-Host $count.GetType()

# Float
[float] $area = 0.0 # cannot use 'F'
Write-Host $area.GetType()

# Double
[double] $circleArea = 0.0 # can use 'D'
Write-Host $circleArea.GetType()

# Decimal
[decimal] $price = 0.0 # cannot use 'M'
Write-Host $price.GetType()

# Boolean
[bool] $isValid = $false
Write-Host $isValid.GetType()

# String
[string] $msg = 'Hello there!'
Write-Host $msg.GetType()

$today = (Get-Date).DateTime
Write-Host $today
Write-Host $today.GetType()

Details: https://renenyffenegger.ch/notes/Windows/PowerShell/language/type/index

Delete variable

To delete the value of a variable:

$cityName = "Tokyo"
Write-Host "City: $cityName"

Clear-Variable -Name cityName # variable name without $
# or $cityName = $null
Write-Host "City: $cityName"

To delete the variable:

$cityName = "Tokyo"
Write-Host "City: $cityName"

Remove-Variable -Name cityName # variable name without $
Write-Host "City: $cityName"

$cityName = "Tokyo"
Remove-Item -Path Variable:\cityName # variable name without $
Write-Host "City: $cityName"