PowerShell スクリプトを実行する

Recipe ID: shell-013

Windows 環境において PowerShell スクリプト (.ps1) を実行する方法を解説します。
セキュリティポリシー(ExecutionPolicy)の影響を受ける可能性がある点に注意が必要です。

前提条件

プラグインのインストールが必要です。

npm run tauri add shell

Permissions (権限) の設定

src-tauri/capabilities/default.json に以下の権限を追加します。

{
    "permissions": [
        ...,
        "shell:allow-open",
        {
            "identifier": "shell:allow-execute",
            "allow": [
                {
                    "name": "powershell",
                    "cmd": "powershell",
                    "args": true
                }
            ]
        }
    ]
}

1. フロントエンドから作成する (TypeScript)

直接 .ps1 ファイルを実行することはできないため、powershell コマンドを経由して実行します。
Windows 11 では powershell.exe (Windows PowerShell 5.1) または pwsh.exe (PowerShell 7) が使われますが、ここでは標準的な powershell を指定します。

import { Command } from '@tauri-apps/plugin-shell';

async function runPsScript() {
  // スクリプトパス (適切にエスケープするか、絶対パスを使用)
  const scriptPath = 'C:\\Users\\Public\\Script.ps1';
  
  const cmd = Command.create('powershell', [
    '-NoProfile',
    '-ExecutionPolicy', 'Bypass',
    '-File', scriptPath
  ]);
  
  const output = await cmd.execute();
  console.log(output.stdout);
}

2. バックエンドから作成する (Rust)

std::process::Commandpowershell を呼び出します。

use std::process::Command;

#[tauri::command]
fn run_ps_script() -> Result<String, String> {
    let script_path = "C:\\Path\\To\\Script.ps1";
    
    let output = Command::new("powershell")
        .args([
            "-NoProfile",
            "-ExecutionPolicy", "Bypass",
            "-File", script_path
        ])
        .output()
        .map_err(|e| e.to_string())?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout.to_string())
}

※ スクリプトファイル自体をアプリに同梱する場合は、リソースとしてバンドルし、@tauri-apps/api/path で実行時にパスを解決する必要があります。