电脑知识

powershell:驱动器变量

2017-10-28  本文已影响8人  成都圣安米悦心理咨询

Powershell中所有不是我们自己的定义的变量都属于驱动器变量(比如环境变量),它的前缀只是提供给我们一个可以访问信息的虚拟驱动器.。例如env:windir,象env:驱动器上的一个”文件”,我们通过$访问它,就会返回”文件”的内容。

直接访问文件路径

通过驱动器直接访问文件路径,也支持物理驱动器,必须把文件路径放在封闭的大括号中,因为正常的文件路径包含两个特殊字符“:”和“”,有可能会被powershell解释器误解。

PS> ${c:/powershell/ping.bat}

@echo off

echo batch File Test

pause

Dir %windir%/system

PS> ${c:autoexec.bat}

REM Dummy file for NTVDM

上述的例子有一个限制,就是${$env:HOMEDRIVE/Powershellping.bat}不能识别,原因是$后花括号中的路径必须是具体的路径,而不能带返回值。

解决方法:

PS> Invoke-Expression "`${$env:HOMEDRIVE/Powershell/ping.bat}"

@echo off

echo batch File Test

pause

Dir %windir%/system

因为反引号”`”放在$前,会把$解析成普通字符,解释器会继续去解析第二个$,发现env:HOMEDRIVE,将其替换成c,到此 Invoke-Expression的参数就变成了${C:/Powershell/ping.bat},继续执行这个表达式就可以了。

查看Powershell支持的驱动器,可以使用Get-PSDrive查看。

NameRootDescription

AA:

AliasDrive containing a view of the aliases stored in session state.

CC:

certX509 Certificate Provider

EE:

EnvThe drive containing a view of the environment variables for the process.

FunctionThe drive containing a view of the functions stored in session state.

HKCUHKEY_CURRENT_USERThe software settings for the current user.

HKLMHKEY_LOCAL_MACHINEThe configuration settings for the local machine.

VariableThe drive containing a view of those variables stored in session state.

WSManRoot of WsMan Config Storage.

PSDrive中的大多都支持直接路径访问,例如可以通过函数路径,访问一个函数的具体实现。

PS> function hellow(){ Write-Host "Hellow,Powershell" }

PS> $function:hellow

param()

Write-Host "Hellow,Powershell"

特殊的变量:子表达式

由 $+圆括号+表达式 构成的变量属于子表达式变量,这样的变量会先计算表达式,然后把表达式的值返回。

例如 变量$(3+6),可以简写成(3+6),甚至可以简写成3+6。子表达式变量也可以嵌套在文本中,例如”result=$(3+6)”。

在处理对象的属性时,会大量的用到表达式变量。例如:

PS> $file=ls Powershell_Cmdlets.html

PS> $file.Length

735892

PS> "The size of Powershell_Cmdlets.html is $($file.Length)"

The size of Powershell_Cmdlets.html is 735892

其实上面的代码可以简化为:

PS> "The size of Powershell_Cmdlets.html is $($(ls Powershell_Cmdlets.html).Length)"

The size of Powershell_Cmdlets.html is 735892

上一篇 下一篇

猜你喜欢

热点阅读