Run a Powershell command (not script) from Excel VBA

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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.

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.

回答1:

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.

Try this out:

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


回答2:

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) & "}" 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!