我一直在调整PowerShell配置文件中的一些脚本,但每次退出PowerShell再重新启动它来加载我对配置文件中脚本所做的更改变得很烦。有没有可能在不退出的情况下重启PowerShell会话?
我一直在调整PowerShell配置文件中的一些脚本,但每次退出PowerShell再重新启动它来加载我对配置文件中脚本所做的更改变得很烦。有没有可能在不退出的情况下重启PowerShell会话?
您可以使用. $profile
来重新加载配置文件。
$profile
,可以在PowerShell中执行new-item -path $profile -itemtype file
来创建。至少我认为这是问题所在。 - mooper这将启动一个新的会话,在同一控制台窗口中重新加载您的配置文件:
Invoke-Command { & "powershell.exe" } -NoNewScope # PowerShell 5
Invoke-Command { & "pwsh.exe" } -NoNewScope # PowerShell 7
或者使用一个更长但更健壮的命令,以下命令应该可以正确地跨版本工作:
Get-Process -Id $PID | Select-Object -ExpandProperty Path | ForEach-Object { Invoke-Command { & "$_" } -NoNewScope }
当然,您将失去之前会话中的所有变量等。
注意:在同一窗口中创建新会话会使父进程在后台运行。 通常,这不是问题,因为当窗口关闭时,父进程(以及任何其他祖先)将终止。 如果这是一个问题,您可能希望向您的配置文件添加以下内容:
$p = Get-Process -Id $PID
If ($p.Parent.Name -eq $p.Name -and !($p.MainWindowTitle))
{
Stop-Process -Id $p.Parent.Id -Force
}
profile.ps1
文件中创建一个别名,以便在对其进行更改时重新加载我的配置文件。这是我找到的唯一可以从别名中运行并更新和重新加载会话的解决方案。已点赞,非常感谢! - Gharbad The Weakexit
命令返回到之前的 pwsh。 - c zpowershell(<yourcommandhere>)
。 - JackChance$profile
中(或者编写一个模块,然后导入到'$profile'中),例如:function Restart-PowerShell{
Start-Process PowerShell # Launch PowerShell host in new window
exit # Exit existing PowerShell host window
}
# Add any alias if you want, for ex. rps (rp already occupied by "Remove-ItemProperty”)
Set-Alias -Name rps -Value Restart-PowerShell
注意:虽然这可能不完全符合你在问题标题中写的“不退出”的要求,但如果实质上你的本意是想要一些重新启动PowerShell主机命令(默认情况下在PS不可用),那么这个方法可以起到作用...
Get-PSHostProcessInfo
返回当前PowerShell会话的信息,允许你确定是否正在运行ISE或不是。function Restart-PowerShell
{
if((Get-PSHostProcessInfo).ProcessName.Contains('powershell_ise'))
{
Start-Process 'powershell_ise.exe'
} else {
Start-Process 'powershell.exe'
}
exit
}
if ((Get-Process -id $pid).ProcessName.contains("powershell_ise"))...
或者稍微改变一下,像这样:if ($host.Name -imatch "ise")...
- Randall Borckreload
,它将简单地重新加载/重启。function reload-Console {
clear
Write-Host "Reload Console"
Get-Process -Id $PID | Select-Object -ExpandProperty Path | ForEach-Object { Invoke-Command { & "$_" } -NoNewScope }
}
New-Alias reload reload-Console
function Reset-Session {
# store this shell's parent PID for later use
$parentPID = $PID
# get the the path of this shell's executable
$thisExePath = (Get-Process -Id $PID).Path
# start a new shell, same window
Start-Process $thisExePath -NoNewWindow
# stop this shell if it's still alive
Stop-Process -Id $parentPID -Force
}
# optional
Set-Alias -Name reset -Value Reset-Session
function refresh ($command) {
cls
pwsh
Exit
}