I am preparing a script, which needs to use some images from same folder as the script. The images are to be shown on WinForms GUI.
$imgred = [System.Drawing.Ima
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.