確定當前PowerShell腳本位置的最佳方法是什么?每當我需要引用一個公共模塊或腳本時,我喜歡使用相對于當前腳本文件的路徑,這樣,我的腳本總能找到庫中的其他腳本。那么,確定當前腳本目錄的最佳標準方法是什么?目前,我正在做:$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)我知道在模塊(.psm1)中你可以使用它$PSScriptRoot來獲取這些信息,但這不會在常規腳本(即.ps1文件)中設置。獲取當前PowerShell腳本文件位置的規范方法是什么?
3 回答

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
# This is an automatic variable set to the current file's/module's directory$PSScriptRoot
PowerShell 2
在PowerShell 3之前,沒有比查詢MyInvocation.MyCommand.Definition
常規腳本屬性更好的方法了 。我在基本上每個PowerShell腳本的頂部都有以下行:
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

陪伴而非守候
TA貢獻1757條經驗 獲得超8個贊
如果要創建V2模塊,可以使用名為的自動變量 $PSScriptRoot
。
從PS>幫助automatic_variable
$ PSScriptRoot 包含正在執行腳本模塊的目錄。 此變量允許腳本使用模塊路徑訪問其他路徑 資源。

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
適用于PowerShell 3.0
$PSCommandPath Contains the full path and file name of the script that is being run. This variable is valid in all scripts.
那么功能是:
function Get-ScriptDirectory { Split-Path -Parent $PSCommandPath}
添加回答
舉報
0/150
提交
取消