Powershell variables are like a box where you can contain information. Generally the box is not type restricted, so you are free to store there information of different types. For example your variable can contain a mix of strings, numbers and some collections or arrays.
$a=2,'test',23.5 $a 2 test 23.5
Although from the Powershell standpoint it is totally ok do not specify type of the variable there is huge benefit in specifying variable types.
First of all your code becomes more readable. When you specify type of your variable person who is reading your code have a pretty good guess how it will be used and for what( here also helps good variable name but this is a story for another blog post).
In order to set variable type you are specifying it before variable name in square brackets, so known casting:
Here is the list of common date types used in Powershell:
[int] 32-bit signed integer [long] 64-bit signed integer [single] Single-precision 32-bit floating point number [double] Double-precision 64-bit floating point number [decimal] A 128-bit decimal value [string] Fixed-length string of Unicode characters [char] A Unicode 16-bit character [byte] An 8-bit unsigned character [bool] Boolean True/False value [DateTime] Date and Time [xml] Xml object [array] An array of values [hashtable] Hashtable object
In addition to common data types you can use any .NET class but you need to instantiate object of that class:
For the list of avaible .NET classes please refer to documentation.
Another huge benefit in specifying data type is built in properties and methods available for the type. Which you get absolutely free and it allows you to do more with your code with the less hassle.
To see all properties and methods available for they object you need to view the data type members using Get-Member cmdlet.
In order to do that we simply pipe our variable to Get-Member:
[char]$a='a' $a | Get-Member
Thanks a lot for reading.
If you have any questions please leave them in a comment section below.