powershell像javascript那样可以定义变量存储数据,powershell声明变量不需要像js那样用var声明,而是直接使用$如
$a = 15 //将15赋值给$a
创建好了变量后,可以通过变量名输出变量,也可以把变量名存在字符串中。但是有个例外单引号中的字符串不会识别和处理变量名。
$a = 15
“$a ” //输出15
‘$a’ //输出$a
查看正在使用的变量
Powershell将变量的相关信息的记录存放在名为variable:的驱动中。如果要查看所有定义的变量,可以直接遍历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
。。。
变量写保护
可以使用New-Variable 的option选项 在创建变量时,给变量加上只读属性,这样就不能给变量重新赋值了。
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,Microsoft.PowerShell.Commands.RemoveItemCommand
但是可以通过删除变量,再重新创建变量更新变量内容。
PS C:\test> del Variable:num -Force
PS C:\test> $num=101
PS C:\test> $num
101
有没有权限更高的变量,有,那就是:选项Constant,常量一旦声明,不可修改
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,Microsoft.PowerShell.Commands.RemoveItemCommand
变量描述
在New-Variable 可以通过-description 添加变量描述,但是变量描述默认不会显示,可以通过Format-List 查看。
PS C:\test> new-variable name -Value "me" -Description "This is my name"
PS C:\test> ls Variable:name | fl *
PSPath : Microsoft.PowerShell.CoreVariable::name
PSDrive : Variable
PSProvider : Microsoft.PowerShell.CoreVariable
PSIsContainer : False
Name : name
Description : This is my name
Value : me
Visibility : Public
Module :
ModuleName :
Options : None
Attributes : {}
网友评论