从PowerShell终端中重新启动PowerShell实例的最有效方法是什么?
目前我做以下操作:
pwsh
这似乎启动了一个新实例,但我不确定这是重新启动进程还是仅仅启动一个新进程。
运行pwsh
只是在当前进程的子进程中启动一个新会话,该会话将继续存在,并在从新进程exit
时返回。
你可能想要的是用一个新的会话替换当前会话。
-
类unix平台 PowerShell (Core)v7.3+,可以使用
exec
(Switch-Process
cmdlet的内置别名函数[1])将用不同的进程替换当前进程:# PS v7.3+, on Unix exec pwsh
- 在v7.2-中,没有简单的解决方案,尽管您可以考虑使用(我的)
ttab
实用程序。
- 在v7.2-中,没有简单的解决方案,尽管您可以考虑使用(我的)
-
Windows,不存在的直接等价:
-
常规控制台窗口(
conhost.exe
),正如Mathias R. Jessen所指出的,你可以达到以下相同的效果:& (Get-Process -Id $PID).Path -NoExit -c "Stop-Process -Id $PID"
-
不幸的是,这在Windows终端中不起作用,但是您可以使用的命令行,
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
}
[1]exec
(现在)是一个函数而不是一个常规别名,由于技术原因:参见GitHub PR #18567以获得解释。