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

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

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

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

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


当前回答

我发现这里发布的旧解决方案在PowerShell V5上对我不起作用。我想到了这个:

try {
    $scriptPath = $PSScriptRoot
    if (!$scriptPath)
    {
        if ($psISE)
        {
            $scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath
        }
        else {
            Write-Host -ForegroundColor Red "Cannot resolve script file's path"
            exit 1
        }
    }
}
catch {
    Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)"
    exit 2
}

Write-Host "Path: $scriptPath"

其他回答

如果您正在创建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.

我需要知道脚本名称以及它在哪里执行。

给MyInvocation结构加上前缀“$global:”,当从主脚本和导入的. psm1库文件的主线调用时,将返回完整的路径和脚本名称。它也可以在导入库中的函数中工作。

在反复折腾之后,我决定使用$global: myinvoke . invocationname。 它可靠地工作与CMD启动,运行与Powershell,和ISE。 本地和UNC发射都返回正确的路径。

我花了一段时间来开发一些东西,把接受的答案变成一个健壮的函数。

我不确定其他人的情况,但我在一个同时使用PowerShell版本2和3的机器的环境中工作,所以我需要同时处理这两个版本。下面的函数提供了一个优雅的回退:

Function Get-PSScriptRoot
{
    $ScriptRoot = ""

    Try
    {
        $ScriptRoot = Get-Variable -Name PSScriptRoot -ValueOnly -ErrorAction Stop
    }
    Catch
    {
        $ScriptRoot = Split-Path $script:MyInvocation.MyCommand.Path
    }

    Write-Output $ScriptRoot
}

这也意味着函数引用Script作用域,而不是Michael Sorens在他的一篇博客文章中概述的父作用域。

非常类似于已经发布的答案,但管道似乎更像powershell:

$PSCommandPath | Split-Path -Parent

你也可以考虑split-path -parent $ pisse . currentfile。如果任何其他方法失败,则返回Fullpath。特别是,如果你运行一个文件来加载一堆函数,然后在ISE shell中执行这些函数(或者如果你run-selected),上面的Get-Script-Directory函数似乎不起作用。