如何在 Powershell 中设置 FromFile 位置?

How to set FromFile location in Powershell?

我正在准备一个脚本,它需要使用与脚本相同的文件夹中的一些图像。图像将显示在 WinForms GUI 上。

$imgred = [System.Drawing.Image]::FromFile("red.png")

当我 运行 手动从文件夹中单击 ps1 脚本时,它会加载图像并显示它们。不幸的是,我不记得我是如何设置它的,但据我所知,它只是用于 ps1 文件的默认程序。 当我 运行 来自 cmd 文件的脚本(隐藏 cmd window)时,它也会加载它们。

但是当我使用 Powershell IDE 和 运行 打开它时,出现错误并且我的 GUI 上没有显示任何图标。 当我用 Powershell 打开时,它也无法加载它们。

我能找到的那些 运行 模式之间的唯一区别是:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$scriptPath             #always same, the location of script
(Get-Location).Path     #scriptlocation when icons loaded, system32 folder when unsuccessful load

执行 cd $scriptPath 时的行为相同,因此当前文件夹很可能不是有罪的文件夹。

我知道我可以在每个文件读取行 (FromFile) 中写入 $scriptPath/red.png,但我想要的是定义一次 - FromFile 的默认位置 - 然后只需简单的文件名工作不管我运行的方式如何。

要更改什么以使默认文件读取路径与我的脚本位置相同?

修改 PowerShell 中的默认位置堆栈 ($PWD) 不会影响主机应用程序的工作目录。

要查看实际效果:

PS C:\Users\Mathias> $PWD.Path
C:\Users\Mathias
PS C:\Users\Mathias> [System.IO.Directory]::GetCurrentDirectory()
C:\Users\Mathias

现在更改位置:

PS C:\Users\Mathias> cd C:\
PS C:\> $PWD.Path
C:\
PS C:\> [System.IO.Directory]::GetCurrentDirectory()
C:\Users\Mathias

当您调用带有文件路径参数的 .NET 方法时,例如 Image.FromFile(),路径是相对于后者解析的,而不是 $PWD

如果要传递相对于 $PWD 的文件路径,请执行:

$pngPath = Join-Path $PWD "red.png"
[System.Drawing.Image]::FromFile($pngPath)

[System.Drawing.Image]::FromFile("$PWD\red.png")

如果您需要相对于执行脚本的路径,在 PowerShell 3.0 和更新版本中,您可以使用 $PSScriptRoot 自动变量:

$pngPath = Join-Path $PSScriptRoot "red.png"    

如果您也需要支持 v2.0,您可以在脚本的顶部放置如下内容:

if(-not(Get-Variable -Name PSScriptRoot)){
  $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Definition -Parent 
}

在交互模式下使用 PowerShell 时,您可以可以prompt 函数配置为具有 .NET "follow you around",如下所示:

$function:prompt = {
    if($ExecutionContext.SessionState.Drive.Current.Provider.Name -eq "FileSystem"){
        [System.IO.Directory]::SetCurrentDirectory($PWD.Path)
    }
    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
}

但我不建议这样做,只是养成提供完全限定路径的习惯。