An important property of a PowerShell variable is its name, which is always preceded by the dollar sign “$” and can only contain letters, numbers, and the underscore. If you feel a strong urge to use other characters, you have to enclose the name in curly braces. You should not use the name of variables that have been pre-defined.
Windows PowerShell uses the Microsoft .NET Framework data types. The poweshell can supports strings ,integers ,floating point numbers, strings, and Boolean values.You don’t have to explicitly declare the data type of a variable, the PowerShell automatically chooses the data type for you when you initialize the variable—that is,when you first assign a value.
Example: 1
1 2 3 |
$GetNumber = Read-Host "Please enter you score" $Total = $GetNumber + $GetNumber Write-Host "The Total Score is $Total" |
PowerShell wrongly assumed that the data type of the variable $GetNumber is String. Because the arithmetic operator + is overloaded (the implementation of the operator depends on the arguments), the second line in the program add a string instead of a number.
The second argument of the operator + always has to be a number, so PowerShell automatically converts the data type of $GetNumber into Int32. However, the first argument can also be a string. The result is that PowerShell determines the value of the expression “5”+5, which is 55 ( concatenate the string).
Example: 2
1 2 3 |
[INT]$GetNumber = Read-Host "Please enter you score" $Total = $GetNumber + $GetNumber Write-Host "The Total Score is $Total" |
In the above code snippet, we explicitly declared the number as Int32 (integer) by enclosing the type name in square brackets before the variable name. So the above variable is called “strongly typed”. If you declare the variable’s data type implicitly in our script the the variable is called as weakly typed.
Data Types:
Data Type Name | Description |
---|---|
[Array] | Array |
[Bool] | Value is TRUE or FALSE |
[DateTime] | Date and time |
[Guid] | Globally unique 32-byte identifier |
[HashTable] | Hash table, collection of key-value pairs |
[Int32], [Int] | 32-bit integers |
[PsObject] | PowerShell object |
[Regex] | Regular expression |
[ScriptBlock] | PowerShell script block |
[Single], [Float] | Floating point number |
[String] | String |
[Switch] | PowerShell switch parameter |
[TimeSpan] | Time interval |
[XmlDocument] | XML document |
Note:
- Windows PowerShell uses the Microsoft .NET Framework data types.
- We don’t have to rely on PowerShell’s ability to automatically convert data types if we tell the interpreter that we are expecting a number as input.
- This ensures that our script works as intended.
- The explicitly declaring variable types can prevent unwanted results in your scripts and makes them more reliable.
Leave A Comment