【问题标题】:How to set FromFile location in Powershell?如何在 Powershell 中设置 FromFile 位置?
【发布时间】:2017-05-18 10:07:29
【问题描述】:

我正在准备一个脚本,它需要使用与脚本相同文件夹中的一些图像。图像将显示在 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 的默认位置 - 然后无论采用何种方式都只需简单的文件名即可我运行它。

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

【问题讨论】:

    标签: winforms powershell location fromfile


    【解决方案1】:

    在 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)) ";
    }
    

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

    【讨论】:

    • 太棒了!谢谢,这一行做到了:[System.IO.Directory]::SetCurrentDirectory($scriptPath)
    猜你喜欢
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2015-11-23
    • 2012-02-04
    • 2020-07-13
    相关资源
    最近更新 更多