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
。。。
查找变量
因为有虚拟驱动variable:的存在,可以象查找文件那样使用通配符查找变量。例如要查询以value打头的变量名。
PS C:test> ls variable:value* Name Value ---- ----- value1 20 value2 10
验证变量是否存在
验证一个变量是否存在,仍然可以象验证文件系统那样,使用cmdlet Test-Path。为什么?因为变量存在变量驱动器中。
PS C:test> Test-Path variable:value1 True PS C:test> Test-Path variable:value2 True PS C:test> Test-Path variable:valueUnkonw False
删除变量
因为变量会在powershell退出或关闭时,自动清除。一般没必要删除,但是你非得删除,也可以象删除文件那样删除它。
PS C:test> Test-Path variable:value1 True PS C:test> del variable:value1 PS C:test> Test-Path variable:value1 False
使用专用的变量命令
为了管理变量,powershell提供了五个专门管理变量的命令Clear-Variable,Get-Variable,New-Variable,Remove-Variable,Set-Variable。因为虚拟驱动器variable:的存在,clear,remove,set打头的命令可以被代替。但是Get-Variable,New-Variable。却非常有用new-variable可以在定义变量时,指定变量的一些其它属性,比如访问权限。同样Get-Variable也可以获取这些附加信息。
变量写保护
可以使用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










