2017-01-04 60 views
0

我正在準備一個腳本,它需要使用與腳本相同的文件夾中的一些圖像。圖像將顯示在WinForms GUI上。如何在Powershell中設置FromFile位置?

$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的默認位置 - 然後只需簡單的文件名工作而不管我運行它的方式。

要更改什麼以便默認的文件讀取路徑與我的腳本位置相同?

回答

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 

當你調用,需要一個文件路徑參數,像Image.FromFile()的.NET方法,是相對路徑解析到後者,而不是$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)) "; 
} 

但我會建議反對的是,剛剛進入提供完全合格的路徑,而不是習慣。

+0

很好的解釋! –

+0

非常好!謝謝,這一行做到了: [System.IO.Directory] ​​:: SetCurrentDirectory($ scriptPath) – uldics