銀河鉄道

【VBA】指定場所にあるPowerShellスクリプトを実行する

サムネイル
[VBA]Run PowerShellfrom VBA

短いスクリプトなら、VBAに直書き

長いスクリプトは直書きができないため、呼び出して実行する

ExcelからPowerShellスクリプトを呼び出すテスト用コード

Public Sub RunScript()
    Dim ws As Worksheet
    Dim scriptPath As String
    Dim targetPath As String
    Dim shellCommand As String

    ' 末尾のバックスラッシュを調整
    Dim basePath As String
    basePath = ThisWorkbook.Path
    If Right(basePath, 1) <> "¥" Then basePath = basePath & "¥"
    scriptPath = basePath & "list.ps1"

    ' ターゲットパスの選択
    #If USE_TEST_PATH Then
        targetPath = Left(TEST_PATH_OUTPUT, Len(TEST_PATH_OUTPUT) - 1)
    #Else
        targetPath = "(指定のパス)"
    #End If

    ' PowerShellコマンドを構築
    shellCommand = "powershell.exe -ExecutionPolicy Bypass -File """ & scriptPath & _
                   """ -Path """ & targetPath & """"

    ' 完了まで待機して実行
    CreateObject("WScript.Shell").Run shellCommand, 1, True
End Sub

目的

このSubは、ExcelからPowerShellスクリプトを呼び出すためのテスト用ランチャー。
list.ps1 を実行し、引数として -Path に指定フォルダを渡す仕組み。

Vocabulary

英語日本語
ExecutionPolicy実行ポリシー
Bypass制限回避モード
Chr(34)二重引用符の文字コード
Shell Functionシェル関数
WScript.ShellWindowsスクリプトホストオブジェクト
Wait for completion完了待機
Safe path concatenation安全なパス結合

外部スクリプト実行時は常に安全性を意識すること。

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧