MENU

マニュアルページで指定したフォルダをクリックで開けるようにするコード

目次

C:\scripts openfolder.ps1

<#
  openfolder.ps1  –  ブラウザの openfolder: URI からフォルダを開く最終版
  2025‑07‑18
#>

param([string]$Path)

# ─ 1. 接頭辞 openfolder: を除去 ───────────────────────────
$Path = $Path -replace '^openfolder:(//)?', ''

# ─ 2. URL デコード → /→\ 変換 → トリム & 制御文字除去 ──────────
Add-Type -AssemblyName System.Web
$decodedPath = [System.Web.HttpUtility]::UrlDecode($Path)
$decodedPath = $decodedPath -replace '/', '\'
$decodedPath = $decodedPath.Trim(' "', "`t", "`r", "`n")
$decodedPath = [regex]::Replace($decodedPath, '\p{C}', '')   # 制御文字全除去

# ─ 3. UNC / ローカル判定 & 正規化 ─────────────────────────
if ($decodedPath -match '^[A-Za-z]:\\') {
    # ローカル (D:\…) はそのまま
}
else {
    # UNC:先頭 / \ を取り除き、\\ を付与
    $decodedPath = '\\\\' + ($decodedPath -replace '^[\\/]+', '')
}

# 先頭に \ が 3 本以上付いていないか最終チェック
while ($decodedPath.StartsWith('\\\')) { $decodedPath = $decodedPath.Substring(1) }

# ─ 4. デバッグログ(任意。不要ならコメントアウト) ──────────────
Add-Content -LiteralPath "$env:TEMP\openfolder_debug.txt" `
    -Value ("[{0}] <{1}>" -f (Get-Date -Format 'HH:mm:ss'), $decodedPath)

# ─ 5. エクスプローラーでフォルダを開く ─────────────────────
Start-Process -FilePath explorer.exe -ArgumentList $decodedPath
param(
    [string]$Path
)

# デバッグ用:受け取った引数を表示
[System.Windows.Forms.MessageBox]::Show("受け取った引数: $Path", "デバッグ")

# openfolder: の接頭辞を削除
if ($Path.StartsWith("openfolder://")) {
    $Path = $Path.Substring(13)
} elseif ($Path.StartsWith("openfolder:")) {
    $Path = $Path.Substring(11)
}

# URLデコード
Add-Type -AssemblyName System.Web
$decodedPath = [System.Web.HttpUtility]::UrlDecode($Path)

# スラッシュをバックスラッシュに変換
$decodedPath = $decodedPath.Replace("/", "\")

# デバッグ用:デコードされたパスを表示
[System.Windows.Forms.MessageBox]::Show("デコードされたパス: $decodedPath", "デバッグ")

# フォルダの存在確認
if (Test-Path $decodedPath -PathType Container) {
    # Explorer でフォルダを開く
    Start-Process explorer.exe -ArgumentList $decodedPath
} else {
    [System.Windows.Forms.MessageBox]::Show("フォルダが見つかりません: $decodedPath", "エラー")
    
    # 親フォルダの確認
    $parentPath = Split-Path $decodedPath -Parent
    if ($parentPath -and (Test-Path $parentPath -PathType Container)) {
        [System.Windows.Forms.MessageBox]::Show("親フォルダは存在します: $parentPath", "情報")
    } else {
        [System.Windows.Forms.MessageBox]::Show("親フォルダも見つかりません: $parentPath", "エラー")
    }
}

# Windows.Forms を読み込み
Add-Type -AssemblyName System.Windows.Forms

テストページ(D:\testテスト test.html)

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>フォルダ開くテスト</title>
</head>
<body>
    <h1>フォルダを開くテスト</h1>
    
    <!-- data-path に "生" のパス -->
    <a data-path="D:\testテスト" class="openfolder">フォルダを開く (D:\testテスト)</a><br><br>
    <a data-path="C:\Users" class="openfolder">フォルダを開く (C:\Users)</a><br><br>
    <a data-path="C:\Program Files" class="openfolder">フォルダを開く (C:\Program Files)</a><br><br>
    
    <div id="debug"></div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const debugDiv = document.getElementById('debug');
    
    document.querySelectorAll('a.openfolder').forEach(a => {
        const raw = a.dataset.path;
        
        // セグメントごとに encodeURIComponent し、/ 区切りで URI 化
        const uri = 'openfolder:' +
            raw.replace(/\\/g,'/').split('/')
               .map(encodeURIComponent).join('/');

        a.href = uri;
        
        // デバッグ情報を表示
        debugDiv.innerHTML += `<p>元のパス: ${raw}<br>変換後URI: ${uri}</p>`;
        
        // クリック時の処理
        a.addEventListener('click', function(e) {
            console.log('クリックされました:', this.href);
            // 必要に応じて preventDefault() を削除
            // e.preventDefault();
        });
    });
});
</script>
</body>
</html>

レジストリファイル(openfolder.reg)

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\openfolder]
@="URL:OpenFolder Protocol"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\openfolder\shell]

[HKEY_CLASSES_ROOT\openfolder\shell\open]

[HKEY_CLASSES_ROOT\openfolder\shell\open\command]
@="powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File \"C:\\scripts\\openfolder.ps1\" -Path \"%1\""
よかったらシェアしてね!
  • URLをコピーしました!

この記事を書いた人

コメント

コメントする

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)

目次