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.

Tim
  • 2,701
  • 3
  • 26
  • 47

2 Answers2

13

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}"""
Bond
  • 16,071
  • 6
  • 30
  • 53
  • 2
    Thanks Bond. Obviously I need to brush up on my PowerShell switches. :/ – Tim Aug 19 '15 at 17:34
  • 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. – Franz Kiermaier Nov 11 '19 at 18:54
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) & "}"
ATek
  • 815
  • 2
  • 8
  • 20