從 PowerShell 終端中重新啟動 PowerShell 實體的最有效方法是什么?
目前我執行以下操作:
pwsh
這似乎啟動了一個新實體,但我不確定這是重新啟動行程還是僅僅啟動一個新行程。
uj5u.com熱心網友回復:
運行只是在當前行程的子pwsh行程中啟動一個新會話,該行程繼續存在,并在您從新行程回傳時回傳。
您可能正在尋找的是用新會話替換當前會話。exit
在類 Unix平臺上,在 PowerShell (Core) v7.3 中,您可以使用( cmdlet
exec的內置別名)將當前行程替換為不同的行程:Switch-Process# PS v7.3 , on Unix exec pwsh- 在 v7.2- 中,沒有簡單的解決方案,但您可以考慮使用 (my)
ttab實用程式。
- 在 v7.2- 中,沒有簡單的解決方案,但您可以考慮使用 (my)
在Windows上,沒有直接的等價物:
正如Mathias R. Jessen指出的那樣,在常規控制臺視窗(
conhost.exe) 中,您可以達到以下相同的效果:& (Get-Process -Id $PID).Path -NoExit -c "Stop-Process -Id $PID"不幸的是,這在Windows Terminal中不起作用,但您可以使用它的CLI,
wt.exe:wt.exe -w 0 -p $env:WT_PROFILE_ID
注意:
前兩個方法繼承了原始會話的環境變數和當前位置(目錄),但沒有別的。
Windows 終端方法不會。
為方便起見,您可以將這些呼叫包裝在自定義的、跨平臺和跨版本的函式中,例如New-Session,您可以將其放入$PROFILE檔案中;您還可以為其定義一個短別名,例如ns:
Set-Alias ns New-Session # define an alias
function New-Session {
$envInheritanceNote = 'Note: Environment was INHERITED from previous session.'
$envNonInheritanceNote = 'Note: Environment was NOT INHERITED from previous session.'
if ($env:OS -eq 'Windows_NT') {
if ($env:WT_PROFILE_ID) { # Windows Terminal
# Windows Terminal: open a new tab in the current window using the same profile, then exit the current tab.
# NOTE:
# * Does NOT inherit the calling shell's environment - only the environment of the master WT executable ('WindowsTerminal'),
# of which there is 1 per window.
# (The tabs of a new window getting launched via wt.exe from a shell in a *regular console window*, for instance, DO inherit the caller's environment.)
# * The `Start-Sleep` call is to prevent the current tab
# from closing instantly, which, if it happens to be the only
# open tab, would close the Windows Terminal window altogether,
# *before* the newly launched tab opens.
wt.exe -w 0 -p $env:WT_PROFILE_ID (Get-Process -Id $PID).Path -NoExit -Command "Write-Verbose -vb '$envNonInheritanceNote'"; Start-Sleep 1; exit
}
else { # regular console window (conhost.exe)
& (Get-Process -Id $PID).Path -NoExit -c "Stop-Process -Id $PID; Write-Verbose -vb '$envInheritanceNote'"
}
}
else {
# Unix
if ($PSVersionTable.PSVersion.Major -gt 7 -or ($PSVersionTable.PSVersion.Major -eq 7 -and $PSVersionTable.PSVersion.Minor -ge 3)) {
# PSv7.3 : use `exec` (built-in alias for `Switch-Process`) to replace the current shell process inside the current window.
exec pwsh -noexit -c "Write-Verbose -vb '$envInheritanceNote'"
}
else { # PSv7.2-: not supported.
throw "Not supported in PowerShell versions up to v7.2.x"
}
}
exit
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/530775.html
標籤:电源外壳
上一篇:根據查找哈希表重命名檔案
