Author : MD TAREQ HASSAN | Updated : 2023/03/16
- In PowerShell, variables begins with a dollar sign (
$) and data type is optional
- Default value of a variable is
- 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
PowerShell core is based on .Net framework, therefore .Net types are available to PowerShell Core.
To get type of a variable:
# 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()
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"