【问题标题】:PowerShell: Is it possible to write a script which refers to files in its folder, which will still work wherever it's called from?PowerShell:是否可以编写一个引用其文件夹中文件的脚本,无论从哪里调用它,它仍然可以工作?
【发布时间】:2013-11-01 21:58:58
【问题描述】:

假设我在 C:\scripts\MyScript.ps1 有一个脚本,它很简单:

Get-Content ".\text.txt"

在 C:\scripts 中,我还有一个文件 text.txt,其中包含在调用脚本时打印的任意文本。如果我在 PowerShell 的当前目录为 C:\scripts 时使用此脚本,它可以正常工作。但是,如果 PowerShell 当前位于不同的目录中,例如C:\otherFolder,然后从 PoSh 命令窗口调用脚本失败:

PS C:\otherFolder> ..\scripts\MyScript.ps1

这是我所期望的,因为脚本中对 text.txt 的引用是相对的,并且该文件不存在于 C:\otherFolder 中。我的问题是,有没有办法编写一个脚本,它具有对其他文件的相对引用,即使从不同的文件夹中调用,它仍然可以按预期工作?

我意识到如果脚本引用“C:\scripts\text.txt”不会有问题,但我希望能够移动脚本(及其依赖文件)而无需更新每次都在脚本中引用。

谢谢。

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    在你的脚本中试试这个:

    $scriptpath = $MyInvocation.MyCommand.Path
    $dir = Split-Path $scriptpath
    $path = join-path $dir "text.txt"
    get-content $path
    

    【讨论】:

      【解决方案2】:

      我认为这个相关的 StackOverflow 问题提供了答案: How to get the current directory of the cmdlet being executed

      您可能希望在脚本中使用$MyInvocation.MyCommand.Path

      【讨论】:

      • 我搜索的时候没找到,但是效果很好,谢谢。已标记我的问题,希望有人将其标记为重复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 2018-08-26
      • 2016-01-12
      相关资源
      最近更新 更多