每当需要引用公共模块或脚本时,我喜欢使用相对于当前脚本文件的路径。这样,我的脚本总能在库中找到其他脚本。

那么,确定当前脚本目录的最佳标准方法是什么?目前,我正在做:

$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

我知道在模块(.psm1)中,您可以使用$PSScriptRoot来获取此信息,但在常规脚本(即.ps1文件)中不会设置此信息。

获取当前PowerShell脚本文件位置的规范方法是什么?


当前回答

我总是使用这个小片段,它以同样的方式为PowerShell和ISE工作:

# Set active path to script-location:
$path = $MyInvocation.MyCommand.Path
if (!$path) {$path = $psISE.CurrentFile.Fullpath}
if ($path)  {$path = Split-Path $path -Parent}
Set-Location $path

其他回答

适用于 PowerShell 3+

function Get-ScriptDirectory {
    if ($psise) {
        Split-Path $psise.CurrentFile.FullPath
    }
    else {
        $global:PSScriptRoot
    }
}

我在我的配置文件中放置了这个函数。它也可以在ISE中使用F8/运行选择。

也许我遗漏了什么…但是如果你想要当前的工作目录,你可以使用这个:(Get-Location)。字符串的路径,对象的Get-Location。

除非你指的是这样的事情,我再看了一遍问题后就明白了。

function Get-Script-Directory
{
    $scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $scriptInvocation.MyCommand.Path
}

如果您正在创建V2模块,您可以使用名为 PSScriptRoot美元。

从PS >帮助自动变量

$PSScriptRoot
       Contains the directory from which the script module is being executed.
       This variable allows scripts to use the module path to access other
       resources.

我总是使用这个小片段,它以同样的方式为PowerShell和ISE工作:

# Set active path to script-location:
$path = $MyInvocation.MyCommand.Path
if (!$path) {$path = $psISE.CurrentFile.Fullpath}
if ($path)  {$path = Split-Path $path -Parent}
Set-Location $path

我使用自动变量$ExecutionContext。 它将在PowerShell 2及更高版本中工作。

 $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.\')

美元的ExecutionContext 对象的engineintrinsic对象 Windows PowerShell主机的执行上下文。你可以 使用此变量查找执行对象 可用于cmdlet。