0

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

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

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

但是当我使用 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 的默认位置 - 然后无论我以何种方式运行它,都只需简单的文件名即可.

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

4

1 回答 1

2

修改 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“跟随您”,如下所示:

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

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

于 2017-01-04T08:09:23.767 回答