
ここではVBAから
・PowerShellファイルを
・同期実行する
方法を記載します!

PowerShellファイルの実行結果も
取得できます!
PowerShellのコード
ここでは例として、
・「PowerShellからのメッセージ出力です!」というメッセージを出力する
・「test.ps1」を作成
します。
$ws = new-object -comobject wscript.shell
$result = $ws.popup("PowerShellからのメッセージ出力です!")
# 正常終了の場合、戻り値として「0」を返す
exit 0
# 異常終了の場合、戻り値として「1」を返す
# exit 1

VBAのコード
ここでは例として、
・上記で作成したPowerShellのファイル「test.ps1」を
・同期実行
します。
※ここでは先程作成したPowerShellのファイル「test.ps1」をデスクトップ配下に配置しています。
'変数の宣言を必須
Option Explicit
Sub execPsFile()
Dim psFile As String
Dim execCommand As String
Dim wsh As Object
Dim result As Integer
'PowerShellファイルのパスを指定
psFile = "C:\Users\user\Desktop\test.ps1"
Set wsh = CreateObject("WScript.Shell")
'実行するコマンドを組み立て
execCommand = "powershell -NoProfile -ExecutionPolicy Unrestricted " & psFile
'PowerShellを実行
result = wsh.Run(command:=execCommand, WindowStyle:=0, WaitOnReturn:=True)
If (result = 0) Then
MsgBox ("Power Shellファイルは正常終了しました。")
Else
MsgBox ("Power Shellファイルは異常終了しました。")
End If
'後片付け
Set wsh = Nothing
End Sub
実行結果
PowerShellファイルを同期実行できました。


参考①
PowerShellファイルだけでなく
・PowerShellのコマンドレットを実行
することもできます。
以下の記事は「PowerShellのコマンドレットを実行」して、当該処理を実現しています。
参考②
VBAで
・Power Shellのコマンドレットの実行結果を取得
することもできます。
詳細は以下の記事をご確認ください。
参考③
VBAで
・バッチファイルを実行
することもできます。
詳細は以下の記事をご確認ください。
参考④
VBAで
・コマンドプロンプトのコマンドを実行
することもできます。
詳細は以下の記事をご確認ください。
参考⑤
VBAで
・VBScriptファイルを実行
することもできます。
詳細は以下の記事をご確認ください。
参考⑥
逆に
・PowerShellファイルからVBAを実行
することもできます。
詳細は以下の記事をご確認ください。
参考⑦
姉妹サイトとして
・PowerShellのノウハウサイト
も運営しています。