11

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.

2 Answers 2

14

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}"""
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Bond. Obviously I need to brush up on my PowerShell switches. :/
I have tried this in a Word macro, but it didn't work in the described way. Passing the PowerShell command without curly braces and surrounding quotation-marks worked for me.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.