【VBA】Run Power Shell file

You can run “Power Shell file“!

Use “Run method” of “WScript.Shell object“!

PR

VBA Code

For example, run following “Power Shell file“:
*Show message.

$ws = new-object -comobject wscript.shell
$result = $ws.popup("Run Power Shell file!")

# Normal return code
exit 0

# Error return code
# exit 1
Power Shell
Power Shell

You can run “Power Shell file” by “Run method” of “WScript.Shell object“.

Option Explicit

Sub sampleProc()

    Dim psFile As String
    Dim wsh As Object
    Dim result As Integer
    
    'Set "Power Shell file path"
    psFile = "C:\Users\user\Desktop\sample.ps1"
    
    Set wsh = CreateObject("WScript.Shell")
    
    'Run the "Power Shell file"
    'Return
    '┗0 : Succeeded
    '┗1 : failed
    result = wsh.Run("powershell -NoProfile -ExecutionPolicy Unrestricted " & psFile, WindowStyle:=0, WaitOnReturn:=True)
    
    If (result = 0) Then
        MsgBox ("Succeeded")
    Else
        MsgBox ("failed ")
    End If
    
    Set wsh = Nothing
    
End Sub

Set “Power Shell path“(Line 10).

Run the “Power Shell file“(Line 18).

If you Hide Power Shell screen, Set WindowStyle to “0”(Line 18).
*If not, set “WindowStyle” to “1”.

If you want wait until the “Power Shell file” finishes, set “WaitOnReturn” to “True“(Line 18).
*If not, set “WaitOnReturn” to “False”.

PR

Result

You ran “Power Shell file

result①
result①
result②
result②
タイトルとURLをコピーしました