Variables are an essential component to store, manage and share data in PowerShell scripts. To create a PowerShell variable, use the $ (dollar sign) symbol.
PowerShell supports several types of variables such as integers, floats, strings, arrays, objects, lists, dictionaries, etc…
In this article, we will discuss how to create a variable in PowerShell and work with various types of variables including initializing, assigning, and modifying values.
Creating Variable in PowerShell
Use the $ (dollar)
sign followed by the name to create a variable in PowerShell.
$jsonString
In the above PowerShell script, the $jsonString
is the variable name.
Initialize and Assigning Values to Variables
Assigning values to a variable in PowerShell is very easy, use the equal sign ( =
) to assign the value to a variable.
$name = "ShellAdmin" $age = "25"
In the above PowerShell script, we have created two variables $name and $age, and assigned values to them.
We have assigned string and integer values to the variables.
You can create a datetime variable in PowerShell using the Get-Date cmdlet.
Modifying Variable Values
In PowerShell, you can modify variable values by reassigning a new value to it.
$age = $age + 2
In the above PowerShell script, the $age
variable value is modified to a new value by reassigning it to an updated value.
You can also use a shorthand operator to modify variables value:
$age += 2
Create Custom Object as Variable
In PowerShell, you can create a custom object as variable other than the supported basic data types.
$customObject = New-Object PSObject -Property @{ Name="ShellAdmin" Age = 27 }
In the above PowerShell script, the New-Object cmdlet is used to create a custom object with properties Name and Age. It creates a PowerShell custom object and assigns it to the variable $customObject
.
The output of the above PowerShell script is:
PS C:\> $customObject = New-Object PSObject -Property @{
Name="ShellAdmin"
Age = 27
}
PS C:\> $customObject
Age Name
--- ----
27 ShellAdmin
Cool Tip: How to create a global variable in PowerShell!
Best Practices for Creating Variables in PowerShell
While creating a variable in PowerShell use descriptive names to improve code readability and maintainability.
Properly initialize a variable before using them in your script and validate user input when assigning values to variables.
Cool Tip: How to check if a variable is null or empty in PowerShell!
Conclusion
I hope the above article on how to create variables in PowerShell, initialize, modifying them is helpful to you.
Variables are an essential part of the script, using the variables effectively, you can create an efficient and powerful script.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.