Powershell 执行上下文


Powershell 提供了一个非常特别的自动化变量,$ExecutionContext。这个变量可能会很少碰到,但是理解它的机制,有助于我们理解Powershell执行命令和脚本的内部机制。这个对象主要包含两个属性:InvokeCommand 和 SessionState.

PS E:> $ExecutionContext

Host           : System.Management.Automation.Internal.Host.InternalHost
Events         : System.Management.Automation.PSLocalEventManager
InvokeProvider : System.Management.Automation.ProviderIntrinsics
SessionState   : System.Management.Automation.SessionState
InvokeCommand  : System.Management.Automation.CommandInvocationIntrinsics

InvokeCommand

到目前为止,我们在Powershell控制台中遇到三个比较特殊的字符,字符串标识双引号,调用操作符 &,和脚本块标识花括号。

特殊字符 定义 内部方法
处理字符串中的变量 ExpandString()
& 执行命令集 InvokeScript()
{} 创建一个新的代码块 NewScriptBlock()
处理变量

每当你在Powershell的字符串中放置一个变量,Powershell解释器会自动处理该变量,并将变量替换成变量本身的值或者内容。

$site = '飞苔博客'
# 双引号中的变量会被自动解析成变量的值:
$text = "我的个人网站 $site"
$text

输出:
我的个人网站 飞苔博客

既然双引号的机制是ExpandString()方法,那么也可以自己调用该方法

$site = '飞苔博客'
# 双引号中的变量会被自动解析成变量的值:
$text = '我的个人网站 $site'
$text
#通过ExpandString()自动处理字符串中的变量
$executioncontext.InvokeCommand.ExpandString($text)

输出:

我的个人网站 $site
我的个人网站 飞苔博客

创建脚本块

如果将Powershell代码放置在花括号中,这样既可以使用调用操作符&执行脚本,也可以将脚本块赋值给一个函数,因为之前的文章中说过,函数是一个命令的脚本块.

# 创建新的脚本块
$block = {
$write=Get-Process WindowsLiveWriter
"$($write.Name) 占用内存: $($write.WorkingSet/1mb) MB"
}
$block.GetType().Name
& $block

# 使用NewScriptBlock方法创建脚本块:
$blockStr='$write=Get-Process WindowsLiveWriter
"$($write.Name) 占用内存: $($write.WorkingSet/1mb) MB"'
$block = $executioncontext.InvokeCommand.NewScriptBlock($blockStr)
$block.GetType().Name
& $block

输出:
ScriptBlock
WindowsLiveWriter 占用内存: 150.734375 MB
ScriptBlock
WindowsLiveWriter 占用内存: 150.734375 MB

执行命令行

输入的命令行可以通过InvokeScript()脚本执行,也可以使用&执行,也可以使用Invoke-Expression命令执行

$cmd='3*3*3.14'
& { 3*3*3.14}
$executioncontext.InvokeCommand.InvokeScript($cmd)
Invoke-Expression $cmd

输出:
28.26
28.26
28.26

SessionState

SessionState是一个用来表现Powershell环境的对象,你同样可以通过自动化变量$ExecutionContext访问这些信息.

PS E:> $executioncontext.SessionState | Format-List *

Drive                         : System.Management.Automation.DriveManagementIntrinsics
Provider                      : System.Management.Automation.CmdletProviderManagementIntrinsics
Path                          : System.Management.Automation.PathIntrinsics
PSVariable                    : System.Management.Automation.PSVariableIntrinsics
LanguageMode                  : FullLanguage
UseFullLanguageModeInDebugger : False
Scripts                       : {*}
Applications                  : {*}
Module                        :
InvokeProvider                : System.Management.Automation.ProviderIntrinsics
InvokeCommand                 : System.Management.Automation.CommandInvocationIntrinsics

PSVariable,可以取出和更新Powershell中所有的变量.

$value = "Test"
# Retrieve variable contents:
$executioncontext.SessionState.PSVariable.GetValue("value")
Test
# Modify variable contents:
$executioncontext.SessionState.PSVariable.Set("value", 100)
$value
100

输出:
Powershell博客 飞苔博客
Powershell博客 网站http://www.mossfly.com

管理驱动器

查看当前驱动器信息

PS E:> $executioncontext.SessionState.Drive.Current

Name Used (GB) Free (GB) Provider   Root CurrentLocation
---- --------- --------- --------   ---- ---------------
E         1.67     78.33 FileSystem E:

查看所有驱动器信息

PS E:> $executioncontext.SessionState.Drive.GetAll() | ft -

Name     Used (GB) Free (GB) Provider    Root
----     --------- --------- --------    ----
WSMan                        WSMan
Alias                        Alias
Env                          Environment
C            44.48     35.52 FileSystem  C:
D            18.69     52.16 FileSystem  D:
E             1.67     78.33 FileSystem  E:
G            52.57    118.55 FileSystem  G:
I            27.31     21.52 FileSystem  I:
Function                     Function
HKLM                         Registry    HKEY_LOCAL_MACHINE
HKCU                         Registry    HKEY_CURRENT_USER
Variable                     Variable
cert                         Certificate
F                            FileSystem  F:
H              .67           FileSystem  H:

如果你的只想关注特定的驱动器,可以使用下面的方法:

PS E:> $executioncontext.SessionState.Drive.GetAllForProvider("FileSystem")

Name Used (GB) Free (GB) Provider   Root CurrentLocation
---- --------- --------- --------   ---- ---------------
C        44.48     35.52 FileSystem C:    Usersbaozhen
D        18.69     52.16 FileSystem D:
E         1.67     78.33 FileSystem E:
G        52.57    118.55 FileSystem G:
I        27.31     21.52 FileSystem I:
F                        FileSystem F:
H          .67           FileSystem H:
路径操作

SessionState的Path包含几个特殊的方法,基本可以覆盖各种常用的路径操作了

方法 描述 对应的命令
CurrentLocation 当前路径 Get-Location
PopLocation() 获取存储的路径 Pop-Location
PushCurrentLocation() 存储路径 Push-Location
SetLocation() 定位路径 Set-Location
GetResolvedPSPathFromPSPath() 相对路径转换成绝对路径 Resolve-Location
本文链接: https://www.pstips.net/powershell-execution-context.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注