How to set FromFile location in Powershell?

谁说胖子不能爱 提交于 2019-12-02 10:45:07

Modifying the default location stack in PowerShell ($PWD) doesn't affect the working directory of the host application.

To see this in action:

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

now change location:

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

When you invoke a .NET method that takes a file path argument, like Image.FromFile(), the path is resolved relative to the latter, not $PWD.

If you want to pass a file path relative to $PWD, do:

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

or

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

If you require a path relative to the executing script, in PowerShell 3.0 and newer you can use the $PSScriptRoot automatic variable:

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

If you need to support v2.0 as well, you could put something like the following at the top of your script:

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

When using PowerShell in interactive mode, you could configure the prompt function to have .NET "follow you around" like so:

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

but I would recommend against that, just get into the habit of providing fully qualified paths instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!