Author : MD TAREQ HASSAN | Updated : 2023/03/16
Declaring variable
- In PowerShell, variables begins with a dollar sign (
$
) and data type is optional - Default value of a variable is
$null
- Data type of a variable:
- PowerShell variables are loosely typed, which means that they aren’t limited to a particular type of object
- A single variable can even contain a collection, or array, of different types of objects at the same time
- PowerShell data types are .Net types (PowerShell core is based on .Net)
# 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:
[byte]
[int]
[long]
[float]
[double]
[decimal]
[bool]
[char]
Reference types:
[string]
[object]
To get type of a variable: .GetType()
.GetType().Name
.GetType().FullName
# 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"