从 Excel VBA 运行 Powershell 命令(不是脚本)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32101010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:55:06  来源:igfitidea点击:

Run a Powershell command (not script) from Excel VBA

vbapowershell

提问by Tim

I've searched SO, and I can find plenty of examples of running a PowerShell script from VBA, but I can't find any examples of just running a simple command.

我搜索了 SO,我可以找到很多从 VBA 运行 PowerShell 脚本的示例,但是我找不到任何仅运行简单命令的示例。

For example, this works:

例如,这有效:

Dim retval As Variant
retval = Shell("PowerShell ""C:\MyScript.ps1""", vbNormalFocus)

But this does not:

但这不会:

Dim retval As Variant
Dim pscmd As String

pscmd = "PowerShell " & _
  Chr(34) & "Get-ScheduledTask" & _
  " -TaskName " & Chr(34) & "My Task" & Chr(34) & _
  " -CimSession MYLAPTOP" & Chr(34)
retval = Shell(pscmd, vbNormalFocus)

Debug.Print pscmd
'pscmd = PowerShell "Get-ScheduledTask -TaskName "My Task" -CimSession MYLAPTOP"

I know I could write the PS command to a file, execute it as a script, and then delete the file, but that does not seem to be very elegant.

我知道我可以将 PS 命令写入文件,将其作为脚本执行,然后删除该文件,但这似乎不是很优雅。

采纳答案by Bond

To run an inline Powershell command, you'll probably need to use the -Commandparam and surround your statement with quotes. It'll also be easier if you use single quotes within the command.

要运行内联 Powershell 命令,您可能需要使用-Commandparam 并用引号将您的语句括起来。如果在命令中使用单引号,也会更容易。

Try this out:

试试这个:

pscmd = "PowerShell -Command ""{Get-ScheduledTask -TaskName 'My Task' -CimSession MYLAPTOP}"""

回答by ATek

Haven't tested but this but the execution policy may be a factor.

尚未测试,但执行策略可能是一个因素。

pscmd = "PowerShell -NoProfile -NoLogo -ExecutionPolicy Bypass -Command {" & _
Chr(34) & "Get-ScheduledTask" & _
  " -TaskName " & Chr(34) & "My Task" & Chr(34) & _
  " -CimSession MYLAPTOP" & Chr(34) & "}"