【问题标题】:How can I get the file system location of a PowerShell script?如何获取 PowerShell 脚本的文件系统位置?
【发布时间】:2011-04-09 16:42:02
【问题描述】:

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

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

例如,此代码将在 DOS 批处理文件中完成它;我正在尝试将其转换为 PowerShell 脚本...

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

【问题讨论】:

  • 只是观察一下您在“DOS”中是如何执行此操作的(我认为在本世纪您指的是 Windows)。这样做不是更好吗:CD "%~dp0"?
  • 在 cmd.exe shell 中可以使用 CD /D "%~dp0" 来完成。

标签: powershell batch-file


【解决方案1】:

PowerShell 3+

运行脚本的路径是:

$PSCommandPath

它的目录是:

$PSScriptRoot

PowerShell 2

运行脚本的路径是:

$MyInvocation.MyCommand.Path

它的目录是:

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

【讨论】:

  • 小心使用$PSSriptRoot。它是模块中的预定义变量。
  • PowerShell team will finally introduce $PSScriptRoot in ordinary scripts - 这就是我所希望的。当我发现这个变量时,我真的很兴奋——我想我可以替换 $MyInvocation / Split-Path 舞蹈,但是不行。 :-) 也想看这个的人应该投票:connect.microsoft.com/PowerShell/feedback/details/522951/…
  • 发生了。如果您使用的是 PowerShell 2 并使用此技巧,请确保编写:if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } 以便它在 PowerShell 3 中“正常工作”
  • 我相信 Split-Path $script:MyInvocation.MyCommand.Path 通常比 Split-Path $MyInvocation.MyCommand.Path -Parent 更受欢迎。有关更多信息,请参阅此帖子:stackoverflow.com/questions/801967/…
  • 注意:如果在 PowerShell ISE 的脚本控制台中键入 $PSScriptRoot 和 $PSCommandPath,或者仅执行脚本文件的选定部分,则 $PSScriptRoot 和 $PSCommandPath 将为空白。如果运行整个脚本,它就可以工作。
【解决方案2】:

罗马库兹明回答了这个问题恕我直言。我只是补充一点,如果你导入一个模块(通过Import-Module),你可以访问模块内的$PsScriptRoot自动变量——它会告诉你模块的位置。

【讨论】:

    【解决方案3】:

    不管怎样,我发现这对我在脚本中的 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"
    

    HTH

    附:包括完整的错误处理。相应地调整您的需求。

    【讨论】:

      【解决方案4】:

      这是一个例子:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多