Variables are the smallest unit of any program or script it saved data in memory. All the programming languages used variables to load some data.
A variable in PowerShell begins with “$” (dollar symbol) and its name can contain any letters, numbers, and underscores. To assign a value to a variable, the “=” operator is used. To display the value of a variable, simply enter the variable on the console.
Example –
$a = 10; $a = “geeks tutorials”
In this example, the variable “a” is the name of the variable and it stored integer as well as string value. Therefore, PowerShell variables do not require data types and any value such as integer, string, float, object, etc. can be stored in a variable.
PowerShell Variable Scope
Like any other programming, the variable scope in PowerShell is either global or local. Local variables are those variables that have a scope within a function or a block of code where they are declared that cannot be accessed outside that scope. While a global variable has a large scope that can be accessed throughout the current PowerShell session. A global variable can be declared like below-
Syntax
$Global: variablename = value
Example-
$Global:myVariable = “This is an explicit global variable”
Types of PowerShell Variables
1.Custom Variables – These variables are created and maintained by the user itself. Users can change, clear, remove these variables anytime.
Example – $a, $Global:myVariable
2.Automatic Variables – Variables that store state information for PowerShell. These variables are created and maintained by Windows PowerShell itself users can’t change the value of these variables.
Example – $Error, $Args, $Event, $Foreach, $Exception etc.
3.Preference Variables – The user preferences for the Windows PowerShell are store in the preference variable. The default value of the preference variable can be changed by the user but these variables are maintained by PowerShell itself.
Example – $ErrorActionPreference, $VerbosePreference, $InformationPreference, $WarningPreference, $DebugPreference, $ConfirmPreference etc.
Reserved Words or Keywords
The Reserved words are those words that cannot be used as a variable name like – if, else, elseif, break, continue, do, for, foreach, function, filter, in, if, return, switch, until, where, while.
These words have special significance in PowerShell hence cannot be used as a variable name.
Strongly typed variable
Although we do not need to specify the data type for a PowerShell variable it can store any type of data but still, it is allowed if we need to create a strongly typed variable. The advantage of creating a strong type variable is to prevent exceptions in later calculations.
How to create a strong type variable –
Need to specify the type in a bracket before the variable name.
Example-
[int]$intvalue = 128 [string]$myStr = "geeks tutorials" [string]$myDateStr = (get-date).ToString("yyyyMM") [datetime]$mystart_date=[datetime]::now.date.addDays(-15)
How to declare a PowerShell Variable
Start with $ sign followed by a variable name and then assign a value by using the “=” operator.
Syntax
$<name of variable> = value;
Example-
$myvar = “Geeks Tutorials”;
This is the popular and the simplest way to declare a variable but the “Set-Variable” cmdlet can also be used to declare and set a PowerShell variable. The Set-Variable Cmdlet also provides various parameters.
Syntax
Set-Variable [-Name] <String[]> [[-Value] <Object>] [-Description <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Option {None | ReadOnly | Constant | Private | AllScope | Unspecified}] [-PassThru] [-Scope <String>] [-Visibility {Public | Private}] [-Confirm] [-WhatIf] [<CommonParameters>]
Parameter Key –
–Name String
The name of the variable use anything in name except some reserved keywords.
-Value Object
The value to assign to the variable.
-Include string
Items upon which Set-variable will act, excluding all others.
-Exclude string
Items upon which Set-variable will not act, include all others.
-Option option
The valid options are:
None: Set no options. (Default)
ReadOnly: The alias cannot be changed unless you use -Force.
Constant: The alias cannot be changed, even by using -Force.
Private: The alias is available only within the scope specified by -Scope. It is invisible in all other scopes.
AllScope: The variable is copied to any new scopes that are created.
-Scope string
The scope in which this alias is valid.
Valid values are “Global”, “Local”, “Private” or “Script”, or a number relative to the current scope (0 through the number of scopes, where Zero is the current scope and 1 is its parent). “Local” is the default.
-force
Create a variable with the same name as an existing read-only variable, Or change the value of a read-only variable. By default, a variable may be overwritten, unless it has an option value of “ReadOnly” or “Constant”. For more information, see the above -Option parameter.
-passThru
Pass the object created by this cmdlet through the pipeline.
-Visibility {Public | Private}
Whether the variable is visible outside of the session, in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users.
When a variable is private, it does not appear in lists of variables, such as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable return an error.
However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined.
-WhatIf
Describe what would happen if you executed the command without actually executing the command.
-Confirm
Prompt for confirmation before executing the command.
-Description string
The description of the variable.
Examples-
Declare a “myVar” variable below and assign some text –
PS C:\> set-variable -name myVar -value “Welcome to geeks tutorials”
Create a global, read-only variable named “myValue” that contains a string:
PS C:\> set-variable -name myValue -value “This is global” -option constant -scope global
Print PowerShell Variable
There are various ways to print or output the PowerShell variable values like in – Powershell console, .txt file, or .CSV file.
Print on Console – use the above commands and try it yourself like below.
Print output on .txt and .csv file–
Use “Out-File” command to print a powershell variable value in .txt file or in .csv file.
PS C:\> set-variable -name myVar -value "Welcome to geeks tutorials" PS C:\> $myVar | Out-File C:\scripts\sample.txt PS C:\> $myVar | Out-File C:\scripts\sample.csv
Note – Make sure the above path should exist otherwise it throws “Could find the path” exception.
Other PowerShell Variable Cmdlet
1.List Variable or Get-Variable
It will list the current variable in PowerShell. Use the below command to get all variables and their value.
Syntax
Get-Variable [[-Name] String[] ]
[-Include string] [-Exclude string]
[-valueOnly] [-scope string] [CommonParameters]
Example 1 –
Use below “Get-Variable” cmdlet to List all current variables.
PS C:\> Get-Variable
OR
PS C:\> ls variable:*
Example 2 –
List all variables that start with letter m.
PS C:\> Get-Variable m*
2.Clear Variable
It will remove the value from a variable. The value will become NULL or (empty) but Clear-Variable cmdlet will preserve the data-type of the object stored in the variable.
Syntax –
Clear-Variable [-name] string[]
[-include string[]] [-exclude string[] ]
[-scope string] [-force] [-passThru] [-whatIf]
[-confirm] [CommonParameters]
Example –
PS C:\> Clear-Variable –name myVar
3. Remove Variable
Completely delete the variable and its value.
Syntax –
Remove-Variable [[-Name] String[] ]
[-Include string] [-Exclude string]
[-scope string] [-force] [-whatIf][-confirm] [CommonParameters]
Example –
PS C:\> Remove-Variable -name MyVar
I hope now you have a detailed understanding of PowerShell variables. Kindly practice the commands with their parameters.