Variables
I have based these notes on this reference. I presume you have already done some programming with me (or someone else), so I'm diving straight in without exhaustive explanation.
The default value of any variable is $null.
Type
Get-Variable
to see what is currently defined by default. The assignment operator is = and I can create a variable and print it as shown below. Run these lines one at a time.
$Rubbish = 1, 2, "a", "££"
$Rubbish
clear-variable -Name Rubbish
$Rubbish
Remove-Variable -Name Rubbish
I can clear the variable after use or set it = $null or I can entirely delete the variable. You can store any type of object in a variable, such as arrays, integers, and strings. But remember, in PowerShell, processes, services, etc are all also objects.
$Rubbish = 1, 2, "a", "££"
$Rubbish.GetType()
Usefully, we can cast a variable, so it has a fixed type.
[int]$Rubbish = 1
$Rubbish.GetType()
If I pass a string to variable, it will automatically convert it.
[int]$Rubbish = 1
$Rubbish = "123456789"
$Rubbish
However, if it’s a string of letters, PowerShell doesn’t do miracles!
[int]$Rubbish = 1
$Rubbish = "This will give you an error!"
$Rubbish
You can translate a date into a datetime object, but the format of the input string is assumed to be US, mmddyyyy.
[datetime]$OGGI = "11/13/2022"
$OGGI
Do some reading and see if you can figure out how to get PowerShell to expect the input string in ddmmyyyy format as we would use in Ireland.
For conversions of variable types, review here.
I can store the output of a command for later use.
$dir_listing = Get-ChildItem c:\
$dir_listing
You can check if a variable exists using test-path variable:\dir_listing When programmes get more complex, it can be tough keeping track of variables. I love this feature!
New-Variable JORzVariable -value 3.142 -description "PI with write-protection" -option ReadOnly
Get-Variable JORzVariable
Notice that this was intended to be a constant, so I also write-protected it.
Last updated