powershellvbscriptprivilege-elevationprocess-elevation

Running Powershell command from within VBScript. The third line of code doesn't run


I am running the following code from VBScript:

Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell.exe -Command ""Start-Process PowerShell -Verb RunAs""")
objShell.run("powershell.exe ""Add-MpPreference -ExclusionPath C:\Windows\Test1\Sub1','C:\Test2'""")

I receive an elevation prompt. After allowing, the last line of code doesn't run.

Separately, the following lines of code work fine in PowerShell. The second line requires elevation, received from line 1,
Powershell -Command "Start-Process PowerShell -Verb RunAs" Add-MpPreference -ExclusionPath 'C:\Test1\Sub1','C:\Test2'

How can I combine these together in a script to run in VBScript? I then want the PowerShell window to close or not open in the first place.

Tried combining them into one line and I also separated them. Neither way works.


Solution

  • This answer explains the required techniques in principle, but there's an additional escaping requirement here to make the call robust:

    Applying all the techniques from the linked answer - hidden, synchronous execution with exit-code capturing - to your use case:

    Set objShell = CreateObject("WScript.Shell")
    
    exitCode = objShell.Run("powershell.exe -Command exit (Start-Process -PassThru -Wait -WindowStyle Hidden -Verb RunAs powershell.exe 'Add-MpPreference -ExclusionPath \\\""C:\Windows\Test1\Sub1\\\"", \\\""C:\Test2\\\""').ExitCode", 0, true)
    
    WScript.Echo "The PowerShell call reported the following exit code: " & exitCode