SoFunction
Updated on 2025-03-10

Windows Powershell Definition Variables

Variables can temporarily save data, so data can be saved in variables for further operation.

#Define variables$a=10
$b=4
#Computing variables$result=$a*$b
$msg="Save text"

#Output variables$result
$msg

40
Save text

Powershell does not need to be declared displayably, and can automatically create variables. Just remember that the prefix of the variable is $.

After creating the variable, you can output the variable through the variable name, or you can store the variable name in a string. But there is an exception that strings in single quotes do not recognize and process variable names.

Select variable name

In powershell, variable names start with the dollar sign "$", the remaining characters can be any characters of numbers, letters, or underscores, and the powershell variable names are case-insensitive ($a and $A are the same variables).

Some special characters have special uses in powershell, and these characters are generally not recommended as variable names. Of course, you have to use it, please enclose the entire variable name suffix in curly braces.

PS C:\test> ${"I"like $}="mossfly"
PS C:\test> ${"I"like $}

mossfly assignment and return value

The assignment operator is "=", which can assign almost any data to a variable, or even a cmdlet command
, Why, because Powershell supports objects, objects can be all-encompassing.

PS C:\test> $item=Get-ChildItem .
PS C:\test> $item

  Directory: C:\test

Mode        LastWriteTime   Length Name
----        -------------   ------ ----
d----    2011/11/23   17:25      ABC
-a---    2011/11/24   18:30   67580 
-a---    2011/11/24   20:04   26384 
-a---    2011/11/24   20:26   12060 alias
-a---    2011/11/24   20:27   12060 alias.ps1
-a---    2011/11/23   17:25     0 
-a---    2011/11/23   17:25     0 
-a---    2011/11/23   17:25     0 
-a---    2011/11/25   11:20    556 
-a---    2011/11/24   17:37    7420 
-a---    2011/11/28   15:30     63 
-a---    2011/11/24   17:44   735892 Powershell_Cmdlets.html
-a---    2011/11/28   17:03     60 test.ps1
-a---    2011/11/23   17:37    242 
-a---    2011/11/28   16:42    170 

PS C:\test> $result=3000*(1/12+0.0075)
PS C:\test> $result
272.5

Assign values ​​to multiple variables at the same time
The assignment operator can not only assign a value to a variable, but also assign the same value to multiple variables at the same time.

PS C:\test> $a=$b=$c=123
PS C:\test> $a
123
PS C:\test> $b
123
PS C:\test> $c
123

Exchange the value of the variable

To exchange the values ​​of two variables, traditional programming languages ​​require at least three steps and also define an intermediate temporary variable.

$Value1 = 10
$Value2 = 20
$Temp = $Value1
$Value1 = $Value2
$Value2 = $Temp

In powershell, exchanging the values ​​of two variables makes this function very simple.

PS C:\test> $value1=10
PS C:\test> $value2=20
PS C:\test> $value1,$value2=$value2,$value1
PS C:\test> $value1
20
PS C:\test> $value2
10

View the variables being used
Powershell stores records of variable related information in a driver named variable:. If you want to view all defined variables, you can directly traverse the variable:

PS C:\test> ls variable:

Name              Value
----              -----
"I"like $           mossfly
$               cls
?               True
^               cls
_
1               1
a               123
args              {}
b               123
c               123
ConfirmPreference       High
ConsoleFileName
DebugPreference        SilentlyContinue
。。。

Find variables

Because there is a virtual driver variable:, you can use wildcard characters to find variables like you can find files. For example, you want to query the name of a variable that is headed by a value.

PS C:\test> ls variable:value*

Name              Value
----              -----
value1             20
value2             10

Verify that the variable exists

Verify that a variable exists, and you can still use cmdlet Test-Path just like you do in verifying the file system. Why? Because variables are present in the variable drive.

PS C:\test> Test-Path variable:value1
True
PS C:\test> Test-Path variable:value2
True
PS C:\test> Test-Path variable:valueUnkonw
False

Delete variables

Because variables will be automatically cleared when powershell exits or closes. Generally, there is no need to delete it, but you have to delete it, and you can delete it like you would delete it.

PS C:\test> Test-Path variable:value1
True
PS C:\test> del variable:value1
PS C:\test> Test-Path variable:value1
False

Use dedicated variable commands

To manage variables, powershell provides five commands specifically for managing variables, Clear-Variable, Get-Variable, New-Variable, Remove-Variable, Set-Variable. Because the virtual drive variable: exists, clear, remove, and set commands headed by the clear, remove, and set can be replaced. But Get-Variable, New-Variable. However, it is very useful. New-variable can specify some other properties of the variable, such as access permissions when defining a variable. Also Get-Variable can get these additional information.

Variable write protection

You can use the option option of New-Variable. When creating a variable, add read-only attributes to the variable, so that the variable cannot be reassigned.

PS C:\test> New-Variable num -Value 100 -Force -Option readonly
PS C:\test> $num=101
Cannot overwrite variable num because it is read-only or constant.
At line:1 char:5
+ $num <<<< =101   + CategoryInfo     : WriteError: (num:String) [], SessionStateUnauthorizedAccessException   + FullyQualifiedErrorId : VariableNotWritable PS C:\test> del Variable:num
Remove-Item : Cannot remove variable num because it is constant or read-only. If the variable is read-only,
ration again specifying the Force option.
At line:1 char:4
+ del <<<< Variable:num
  + CategoryInfo     : WriteError: (num:String) [Remove-Item], SessionStateUnauthorizedAccessExcepti
  + FullyQualifiedErrorId : VariableNotRemovable,

However, you can update the variable content by deleting the variable and recreating the variable.

PS C:\test> del Variable:num -Force
PS C:\test> $num=101
PS C:\test> $num
101

Is there a variable with higher permissions? There is one, that is: option Constant, once the constant is declared, it cannot be modified.

PS C:\test> new-variable num -Value "strong" -Option constant

PS C:\test> $num="why? can not delete it."
Cannot overwrite variable num because it is read-only or constant.
At line:1 char:5
+ $num <<<< ="why? can not delete it."   + CategoryInfo     : WriteError: (num:String) [], SessionStateUnauthorizedAccessException   + FullyQualifiedErrorId : VariableNotWritable PS C:\test> del Variable:num -Force
Remove-Item : Cannot remove variable num because it is constant or read-only. If the variable is read-only,
ration again specifying the Force option.
At line:1 char:4
+ del <<<< Variable:num -Force
  + CategoryInfo     : WriteError: (num:String) [Remove-Item], SessionStateUnauthorizedAccessExcepti
  + FullyQualifiedErrorId : VariableNotRemovable,

Variable description
In New-Variable, variable description can be added through -description, but variable description will not be displayed by default and can be viewed through Format-List.

PS C:\test> new-variable name -Value "me" -Description "This is my name"
PS C:\test> ls Variable:name | fl *

PSPath    : ::name
PSDrive    : Variable
PSProvider  : 
PSIsContainer : False
Name     : name
Description  : This is my name
Value     : me
Visibility  : Public
Module    :
ModuleName  :
Options    : None
Attributes  : {}