
我經常與無法輕易更改的批次腳本進行互動工作。該腳本的功能之一是作為導航輔助- 它了解我的公司/產品的程式碼佈局約定,並使用該知識將“theScript cdTestCode”轉換為“cd /DC:\The\Inferred\Path\To\The\ Unit” \Tests」代表我目前所在目錄的元件。
我希望能夠在互動式 PowerShell 環境中使用此腳本。對於它的大部分功能,只需從 PowerShell 中呼叫腳本就可以了。但對於該導航功能,它執行的目錄更改只會影響 PowerShell 在其中運行批次腳本的 cmd 環境。 PowerShell 作為我的shell。
所以我的問題是:假設我無法更改批次腳本(而且我不想將其重寫為 PowerShell 腳本),有沒有什麼好的方法可以在批次腳本完成時將批次腳本的最終工作目錄傳播回 PowerShell 主機?也就是說,是否有相當簡單的方法來寫函數:
function InvokeBatchScriptAndAssumeDirectory($BatchScriptFullName) {
# ...
}
這樣
PS> pwd
Path
----
C:\elsewhere
PS> echo .\mybatchscript.cmd
@ECHO OFF
cd /D C:\
PS> InvokeBatchScriptAndAssumeDirectory .\mybatchscript.cmd
PS> pwd
Path
----
C:\
這個問題非常相似,但它提出的“解決方案”只是將批次檔更改為 .ps1 腳本。我正在使用的批次腳本非常複雜 - 這樣做需要大量重寫,我希望避免這種情況。
答案1
我最終同意了@dangph 的建議。
Param([string]$Script, [string]$ScriptParams)
$WorkingDirectoryTempFile = [IO.Path]::GetTempFileName()
cmd /c " `"$Script`" $ScriptParams && cd > `"$WorkingDirectoryTempFile`" "
Get-Content $WorkingDirectoryTempFile | Set-Location
Remove-Item $WorkingDirectoryTempFile
順便說一句,Lee Holmes 在 2006 年寫了一個腳本,解決了基本上相同的問題:http://www.leeholmes.com/blog/2006/05/11/nothing-solves-everything-%e2%80%93-powershell-and-other-technologies/