如何在powershell中执行变量中的字符串

How to execute a string in a variable in powershell

我有以下字符串

"C:\ProgramData\Package Cache{6b95042e-f763-4850-9136-d004dd0d0a9b}\AzInfoProtection.exe" /uninstall

我需要按如下方式执行上面的字符串

First-line

cd C:\ProgramData\Package Cache\{6b95042e-f763-4850-9136-d004dd0d0a9b}

The second line (note there is no exe)

AzInfoProtection /uninstall

变量通常在 PowerShell 中执行如下所示

Invoke-Expression $cmd

但是如何将上面的字符串拆分成多行执行。然后我需要删除引号然后执行。

这里的问题有点难以理解,但我想我明白了。如果我有误或误解了您的意图,请告诉我。

$commandString = '"C:\ProgramData\Package Cache{6b95042e-f763-4850-9136-d004dd0d0a9b}\AzInfoProtection.exe" /uninstall'

# Get command parent directory
if( $commandString -match '^".*?"' ) {
  $runInDir = Split-Path -Parent $Matches[0]
}

# Change directories (use the location stack for easy traversal) 
Push-Location $runInDir

# Run program
Invoke-Expression $commandString

# Change back to previous directory
Pop-Location

这通过检查字符串是否以引号括起的字符串开头(转义引号不需要在文件路径中处理)来工作,如果是,则从 $Matches 对象获取第一个匹配项。 $Matches 是一个自动变量,只要您使用 [-match operator][1] 得到 $True 结果,它就会被填充。提取命令路径后,我们使用 Split-Path 获取相对于文件路径的父容器。

然后使用 Push-Location to change directories. Push-Location works like Set-Location (aliased to cd) except it tracks the directories you leave and enter as a stack. Its sibling cmdlet Pop-Location 进一步使用到 return 到以前的位置。

最后,我们用Invoke-Expression来运行你的命令。完成后使用Pop-Location到return到上一级目录。请记住以下几点:

You should take note that the use of Invoke-Expression is often implemented insecurely, and so you should consider heeding the warning on the documentation I've linked to and consider parameterizing your command if your $commandString is actually populated from a generated file, provided by a parameter, or another other outside source.


注意:您在问题中提到了这一点:

The second line (note there is no exe)

Windows 不关心在执行它们时是否省略了可执行类型的扩展名。您可以 运行 AzInfoProtection.exe 带或不带 .exe 最后。因此,除非我遗漏了什么,否则这个细节与这段代码的工作方式没有任何关系。

到 运行 字符串,你可以通过管道将它传送到 cmd 到 运行 它使用:

$commandString | cmd