从 Excel VBA 运行 Powershell 命令(不是脚本) [英] Run a Powershell command (not script) from Excel VBA

查看:512
本文介绍了从 Excel VBA 运行 Powershell 命令(不是脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如,这有效:

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

但这不会:

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"

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

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.

推荐答案

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

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

试试这个:

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

这篇关于从 Excel VBA 运行 Powershell 命令(不是脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆