All scripting languages use placeholders or variables to hold data. Each language has its own rules and symbols. I have found that PowerShell variables are straightforward, just remember to introduce your variable with a dollar sign, for example: $Memory
PowerShell has no built-in mechanism for enforcing variable types, for example, string variables can begin with letters or numbers. Yet numeric variables can also begin with letters (or numbers). However, you can restrict the values of a PowerShell variable by declaring the datatype [int] or [string].
Example 1a: Declaring a PowerShell Variable as an Integer
# Declaring PowerShell Integer Variable
[int]$a =7
$a +3
$a #To print the value stored in variable
# PS>10
Example 1b: “Twenty” is not an [int]
# Declaring PowerShell Integer Variable
[int]$a =7 #$a is capable of holding integer values only
$a =”Twenty” #Trying to assign a String value
$a #To print the value stored in variable
# PS> Error “Cannot Convert value.
Note 1: Declaring the datatype is [optional]. But , If it is declared it won’t accept any other datatypes to merge within it.
Example 2: Declaring the Variable Without Specifying the Type.
$b = 7 #$b is not defined with any datatype
$b = “Twenty”
$b #To print the value stored in variable
# PS> Twenty
Note 2: There is no error here because $b was not declared as number or a string.
Powershell is case sensitive or case insensitive?
Do you think that PowerShell variables are case sensitive, or case insensitive? The answer is insensitive, just as with most other PowerShell commands, upper or lower case work equally.
Example 3: Declaring the Variable as $b and printing the variable as $B
$b = 7 #$b is not defined with any datatype
$b = “Twenty”
$B #To print the value stored in variable
# PS> Twenty
Reserved Words – Not to Be Used For Variables
Avoid using these reserved keywords for your variables.
- Break
- continue
- do
- else
- ElseIf
- for
- foreach
- function
- filter
- in
- if
- return
- switch
- until
- where
- while
Declaring Multiple Variables
In scripting we are always seeking ways of writing tighter code. In the case of variables you could make multiple declarations on the same line
Example 5: Assigning multiple variables values in a single line
$DriveA, $DriveB, $DriveC, $DriveD = 250, 175, 330, 200