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

时间:2015-08-19 16:30:21

标签: vba powershell

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

例如,这有效:

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命令写入文件,将其作为脚本执行,然后删除该文件,但这似乎不是很优雅。

2 个答案:

答案 0 :(得分:10)

要运行内联Powershell命令,您可能需要使用IL_0000: nop IL_0001: ldarg.0 IL_0002: ldfld int32 SyringeWpfTest.ILTesting::'<Counter>k__BackingField' IL_0007: ldarg.1 IL_0008: ceq IL_000a: ldc.i4.0 IL_000b: ceq IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: brfalse.s IL_001a IL_0011: nop IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: stfld int32 SyringeWpfTest.ILTesting::'<Counter>k__BackingField' IL_0019: nop IL_001a: ret 参数并用引号括起您的语句。如果在命令中使用单引号,也会更容易。

试试这个:

IL

答案 1 :(得分:0)

Haven未经过测试,但执行政策可能是一个因素。

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