如何获取PowerShell脚本的文件系统位置?

68

我有一个位于D:\temp的PowerShell脚本。

当我运行这个脚本时,我想要列出该文件的当前位置。我该怎么做?

例如,下面的代码可以在DOS批处理文件中完成此操作; 我正在尝试将其转换为PowerShell脚本...

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"

1
关于你在“DOS”中的操作(我猜你指的是Windows),我有一个观察。你不觉得直接这样做会更好吗:CD“%~dp0”? - Jamie
在cmd.exe shell中,可以使用CD /D“%〜dp0”来完成。 - lit
4个回答

146

PowerShell 3+

正在运行脚本的路径为:

$PSCommandPath

它的目录是:

$PSScriptRoot

PowerShell 2

正在运行脚本的路径为:

$MyInvocation.MyCommand.Path

它的目录是:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent

2
请小心使用$PSScriptRoot。它是模块内的预定义变量。 - Keith Hill
1
PowerShell团队终于将在普通脚本中引入$PSScriptRoot,这正是我所期待的。当我发现这个变量时,我真的很兴奋——认为我可以替换$MyInvocation/Split-Path的操作,但是没有。:-)那些也想看到这一点的人应该投票:https://connect.microsoft.com/PowerShell/feedback/details/522951/psscriptroot-only-works-with-modules - Keith Hill
21
发生了那件事。如果你正在使用这个技巧并且在 PowerShell 2 上操作,请确保写上这句话:if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent },这样它才能在 PowerShell 3 中“正常工作”。 - Jaykul
4
我认为Split-Path $script:MyInvocation.MyCommand.Path通常比Split-Path $MyInvocation.MyCommand.Path -Parent更受欢迎。有关更多信息,请参阅此帖子:https://dev59.com/F3RA5IYBdhLWcg3w2x0I - deadlydog
11
值得注意的是:如果在PowerShell ISE的脚本控制台中键入$PSScriptRoot和$PSCommandPath,则它们将为空,或者如果仅执行脚本文件的选定部分,则也会为空。只有在运行整个脚本时才起作用。 - CodeManX
显示剩余4条评论

11

Roman Kuzmin给出了他的看法。我想补充一下,如果你通过Import-Module导入一个模块,那么你可以在模块内访问$PsScriptRoot自动变量--它会告诉你模块所在的位置。


1

就我个人而言,我发现这在PowerShell V5中对于脚本和PowerShell ISE都适用:

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"

希望有所帮助

附带完整的错误处理。根据您的需求进行调整。


0

这里有一个例子:

$ScriptRoot = ($ScriptRoot, "$PSScriptRoot" -ne $null)[0]
import-module $ScriptRoot\modules\sql-provider.psm1
Import-Module $ScriptRoot\modules\AD-lib.psm1 -Force

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接