如何在 PowerShell 中獲取當前正在執行指令碼的路徑?


要獲取指令碼的完整路徑,我們需要使用 **$myInvocation** 命令。這是一個自動變數,僅在執行指令碼或函式時才會呼叫。

$MyInvocation.MyCommand.Path 命令用於獲取指令碼所在的完整路徑,而 $MyInvocation.MyCommand.Name 用於獲取指令碼的名稱。

示例

$mypath = $MyInvocation.MyCommand.Path
Write-Output "Path of the script : $mypath"

輸出

PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Path of the script : C:\Temp\TestPS.ps1

請注意,我們正在從 System32 目錄執行上述指令碼,輸出路徑為 **C:\temp**。要獲取指令碼目錄,我們可以使用 Split-Path 命令。例如,

Split-Path $mypath -Parent

要獲取指令碼的名稱,可以使用前面提到的 Name 屬性。

示例

$ScriptName = $MyInvocation.MyCommand.Name
Write-Output "`nName of the script : $scriptname"

輸出

PS C:\WINDOWS\system32> C:\Temp\TestPS.ps1
Name of the script : TestPS.ps1

當您直接從控制檯執行上述命令時,它不會輸出任何內容,因為 **$MyInvocation** 僅在呼叫指令碼時才會產生輸出。例如,

更新於: 2023年11月1日

40K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.