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

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

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

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

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


当前回答

适用于 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
}

其他回答

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

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

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

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

如果你想从相对于脚本运行位置的路径加载模块,比如从“lib”子文件夹中,你需要使用以下方法之一:

$PSScriptRoot,它在作为脚本调用时工作,例如通过PowerShell命令 psISE.CurrentFile美元。FullPath,当你在ISE中运行时

但如果你都不在PowerShell中,只是在PowerShell中输入,你可以使用:

pwd。路径

你可以将这三个变量中的一个赋值给一个名为$base的变量,这取决于你运行的环境,如下所示:

$base=$(if ($psISE) {Split-Path -Path $psISE.CurrentFile.FullPath} else {$(if ($global:PSScriptRoot.Length -gt 0) {$global:PSScriptRoot} else {$global:pwd.Path})})

然后在你的脚本中,你可以这样使用它:

Import-Module $base\lib\someConstants.psm1
Import-Module $base\lib\myCoolPsModule1.psm1
#etc.

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

$PSCommandPath | Split-Path -Parent

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