スクリプト自身のパスを取得する

$MyInvocation

「$MyInvocation」はスクリプト実行時、スクリプト自身の情報を格納しています。

スクリプト自身のパスは、

$MyInvocation.MyCommand.Path

スクリプト名は、

$MyInvocation.MyCommand.Name

に格納されています。



では、サンプルです。

まず、以下の3つのスクリプトを用意します。

C:\TestA\a.msh
Write-Host '【a.msh】'
Write-Host $MyInvocation.MyCommand.Path
Write-Host $MyInvocation.MyCommand.Name
Write-Host (parse-path $MyInvocation.MyCommand.Path -parent)
C:\TestB\b.msh
Write-Host '【b.msh】'
Write-Host $MyInvocation.MyCommand.Path
Write-Host $MyInvocation.MyCommand.Name
Write-Host (parse-path $MyInvocation.MyCommand.Path -parent)
C:\TestC\c.msh
Write-Host '【c.msh】'
Write-Host $MyInvocation.MyCommand.Path
Write-Host $MyInvocation.MyCommand.Name
Write-Host (parse-path $MyInvocation.MyCommand.Path -parent)


次に、以下を実行してみます。

MSH C:\> .\TestA\a.msh | .\TestB\b.msh | .\TestC\c.msh
【a.msh】
C:\TestA\a.msh
a.msh
C:\TestA
【b.msh】
C:\TestB\b.msh
b.msh
C:\TestB
【c.msh】
C:\TestC\c.msh
c.msh
C:\TestC

が取得できました。