0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WSL でも簡単に open (Windows の規定のアプリで開く) したい

Last updated at Posted at 2023-04-26

概要

WSL 上の特定のファイルを Windows の規定のアプリで開きたいという内容です。同じことをしている記事は他にもありましたが Powershell を使って簡単に規定のアプリで実行する方法を書いているところがあまりなかったので書きました。

スクリプト

スクリプト全体です。

function open_in_windows() {
    path=$(wslpath -aw $1 | sed -e 's/ /\ /')
    "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe" -Command "& {Invoke-Item $path}"
}

if [ $# -lt 1 ]; then
    open_in_windows "$(pwd)"
else
    for path in "$@"; do
        if [ -e "$path" ]; then
            open_in_windows "$path"
        else
            echo "file or directory $path does not exist."
        fi
    done
fi

open_in_windows 関数

特定のパスを Windows の規定のアプリで開く関数です。以下の動作をしています。

  1. WSL 上でのパスを Windows 上でのパスに変換する
  2. powershell.exe を呼び出し Invoke-Item コマンドレットでパスに対し規定のアクションを実行する

powershell.exe はコマンドライン引数で -Command オプションを指定し、先頭に & をつけてコードブロックを文字列として渡すとそのコマンドを実行してくれます (ドキュメント) 。また、Powershell の Invoke-Item コマンドレットはパスに対して規定のアクションを実行します。

その他の部分

引数がある場合そのパスの存在を検証してから open_in_windows 関数を呼び出します。引数がない場合は . が指定されたものとしてカレントディレクトリを開きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?