前回は、Linuxの環境変数PATHに収められているコマンドをフルパスのリストとして得られるようにした。これは、Linuxの環境変数PATHが本来持っている検索の優先順位を反映させるためだ。 取得するコマンドのパスをフルパスに変更することで、どこのパスのLinuxコマンドが実行されているのかわかるようになった。次のスクリプトが、該当する変更部分だ。

$_linux_command_paths = (
    wsl ls -d ($_linux_path[($_linux_path.length-1)..0] -replace "$","/*")
) 2> $null

スクリプト自体は短いが、PowerShellを利用する上で重要ないくつかのティップスが使われている。以下に、このスクリプトのポイントをもう一度まとめておこう。

  1. 配列の中身を逆順で使う
  2. 配列の中身に対して個々に文字列置換を実施
  3. 文字列置換を正規表現で指定
  4. エラーメッセージを削除
  5. 実行結果を変数などに代入せずにそのまま利用


今回はこのデータをこれまでに作成した$PROFILEに適用して、コマンド実行の優先順位をPowerShell側で制御できるように書き換える。

フルパスを活用する処理に変更する

まずLinuxコマンドを関数でラッピングするためのスクリプトをチェックする。これまでは次のようになっていた。

ForEach($n in $_linux_command_names) {
    if ($n -ne "") {
        $_linux_functions += "
            function $n {
                if (`$Input.Length) {
            `$Input.Reset()
                    `$Input | wsl $n `$(_path_to_linux `$Args)
        }
        else {
                    wsl $n `$(_path_to_linux `$Args)
        }
            }"
    }
}

先に結果を掲載しておく。上記を次のように書き換えることで、今回の目的を達成できる。

ForEach($n in $_linux_command_paths) {
    $_n = (Split-Path -Leaf $n)
    $_linux_functions += "
        function $_n {
            if (`$Input.Length) {
                `$Input.Reset()
                `$Input | wsl $n `$(_path_to_linux `$Args)
            }
            else {
                wsl $n `$(_path_to_linux `$Args)
            }
        }"
}
Remove-Variable n
Remove-Variable _n

では、細かく見ていこう。まず、これまでコマンド名だけでループを回していた部分を、次のようにフルパスのコマンドリストで回すように変更する。これで変数$nにはフルパスのコマンドが代入されていることになる。

ForEach($n in $_linux_command_paths) {

ただし、関数名はフルパスではなくコマンド名で作成するので、フルパスからコマンド名を取り出す必要がある。その処理を行っているのが次の処理だ。

    $_n = (Split-Path -Leaf $n)

この処理で変数$_nにコマンド名(ファイル名)が入ることになる。コマンド名だけを取り出す方法はほかにもあり、文字列の加工処理などを使ってもよいだろう。ここでは、記述が簡単な上記の処理を使った。

関数を定義している部分が、次のように書き換わることになる。

        function $_n {

以下の2つの行に関しては、記述自体はこれまでと同じだ。

`$Input | wsl $n `$(_path_to_linux `$Args)
 wsl $n `$(_path_to_linux `$Args)

ただし、変数$nにはコマンド名ではなくフルパスが入っている。つまり、wslにフルパスを指定してコマンドを実行する処理に変わっていることになる。これで書き換え完了だ。

次の2行はおまけだ。一応、ここだけでしか使っていない変数なので、必要性がなくなった時点で変数を削除している。

Remove-Variable n
Remove-Variable _n

動作を確認してみよう

書き換えた$PROFILEでPowerShellを起動して動作を確かめてみる。$_linux_command_pathsと$_linux_functionsは消さずに残してあるので、その中身を確認してみよう。まず、$_linux_command_pathsを確認すると、次のようになっている。

$_linux_command_pathsの中身を確認

優先順位の低いパスのコマンドが最初に表示され、優先順位の高いパスが最後に表示されていることがわかる。ここまでは前回と同じだ。次に$_linux_functionsの中身を確認すると、次のようになっていることがわかる。

$_linux_functionsの中身を確認

wslで指定しているコマンドがこれまでのコマンド名だけからフルパスに変わっていることがわかる。実際には変更する前と後で実際に実行されるコマンドに違いはないのだが、今回の書き変えでPowerShell側から実行するコマンドを制御しやすい状態にはなった。PowerShellの動作例としても、簡単なわりに効果が見込みやすいものだと言えるだろう。

これまでに作ってきた$PROFILEによって、このPowerShellはLinux側のコマンドをかなりシームレスに実行できるようになった。普段LinuxやmacOSのターミナルで作業をしている方であれば、この環境は結構なじみやすいのではないかと思う。まだいくつかの点で不便なところが残っているので、そのあたりをチューニングしていけば、PowerShellとWindows側のコマンド、そしてLinuxのコマンドをさらにシームレスに実行できるようになるはずだ。

付録: $PROFILE

本連載時点での$PROFILEを次に掲載しておく。

# Copyright (c) 2020 Daichi GOTO <daichi@ongs.co.jp>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.

# author: Daichi GOTO (daichi@ongs.co.jp)
# first edition: Mon Jun 22 18:20:36 JST 2020

#========================================================================
# Definition of Linux commands used via wsl
#========================================================================
$_linux_path = (wsl echo '$PATH').Split(":") -NotMatch "/mnt"
$_linux_command_paths = (
    wsl ls -d ($_linux_path[($_linux_path.length-1)..0] -replace "$","/*")
) 2> $null

# Generate Linux command functions
ForEach($n in $_linux_command_paths) {
    $_n = (Split-Path -Leaf $n)
    $_linux_functions += "
        function $_n {
            if (`$Input.Length) {
                `$Input.Reset()
                `$Input | wsl $n `$(_path_to_linux `$Args)
            }
            else {
                wsl $n `$(_path_to_linux `$Args)
            }
        }"
}
Remove-Variable n
Remove-Variable _n

$_linux_functions += @'
    function _path_to_linux {
        $linuxpath = @()

        # Convert arguments to Linux path style
        ForEach($winpath in $Args) {
            if ($winpath -eq $null) {
                Break
            }

            # Change drive path to mount path
            if ($winpath -match '^[A-Z]:') {
                $drive = $winpath.Substring(0,1).ToLower()
                $linuxpath += "/mnt/" + $drive + $winpath.Substring(2).Replace('\','/')
            }
            # Option is not converted
            elseif ($winpath -match '^[-+]') {
                $linuxpath += $winpath
            }
            # Other argument is converted
            else {
                $linuxpath += ([String]$winpath).Replace('\','/')
            }
        }

        $linuxpath
    }
'@

# Prepare temporary file path with extension .ps1
$_temp = New-TemporaryFile
$_temp_ps1 = $_temp.FullName + ".ps1"
Remove-Item $_temp

# Write function definition to temporary .ps1 file and parse
$_linux_functions | Out-File $_temp_ps1
. $_temp_ps1
Remove-Item $_temp_ps1

# Delete unnecessary variables
Remove-Variable _temp
Remove-Variable _temp_ps1
#Remove-Variable _linux_path
#Remove-Variable _linux_command_paths
#Remove-Variable _linux_functions

#========================================================================
# Individual Linux command function definitions
#========================================================================
# grep
function grep {
    $pattern_exists = $False
    $path_exists = $False
    $skip = $False
    $i = 0

    ForEach($a in $Args) {
        if ($skip) {
            $skip = $False
            $i++
            continue
        }

        # Options without argumetn
        if ($a -cmatch '^-[abcdDEFGHhIiJLlmnOopqRSsUVvwxZ]') {
        }
        # Options with argument
        elseif ($a -cmatch '^-[ABC]') {
            $skip = $True
        }
        # Pattern file specification option
        elseif ($a -ceq '-f') {
            $skip = $True
            $pattern_exists = $True
            $Args[$i+1] = _path_to_linux $Args[$i+1]
        }
        # Pattern specification option
        elseif ($a -ceq '-e') {
            $skip = $True
            $pattern_exists = $True
        }
        # Pattern or file path
        elseif ($a -cnotmatch '^-') {
            if ($pattern_exists) {
                $path_exists = $True
            }
            else {
                $pattern_exists = $True
            }
        }

        $i++
    }

    # Change file path
    if ($path_exists) {
        $Args[-1] = _path_to_linux $Args[-1]
    }

    $Input | wsl grep $Args
}

# ls
Get-Alias ls *> $null && Remove-Item alias:ls
function ls { wsl ls --color=auto $Args }
function ll { ls -l }
function la { ls -a }

#========================================================================
# Alias definition
#========================================================================
Set-Alias -Name open -Value explorer
Set-Alias -Name edge -Value "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
Set-Alias -Name chrome -Value "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"