阻止Powershell退出
我知道PowerShell有一个小小的阻止Powershell退出,powershell,powershell-2.0,powershell-remoting,Powershell,Powershell 2.0,Powershell Remoting,我知道PowerShell有一个小小的-noexit开关 有没有办法不用那个开关就呆在壳里 换句话说,我需要一个脚本命令,它执行后会使shell保持打开状态。像这样吗 PowerShell -File c:\myscript.ps1 -NoExit 我不知道您可以在脚本中运行一个命令,如果没有使用-noexit命令调用shell,该命令将阻止shell退出 如果我不想关闭shell,我通常在末尾使用readhost“按ENTER键继续”。但是,如果未使用-noexit启动shell,则这不会
-noexit
开关
有没有办法不用那个开关就呆在壳里
换句话说,我需要一个脚本命令,它执行后会使shell保持打开状态。像这样吗
PowerShell -File c:\myscript.ps1 -NoExit
我不知道您可以在脚本中运行一个命令,如果没有使用
-noexit
命令调用shell,该命令将阻止shell退出
如果我不想关闭shell,我通常在末尾使用
readhost“按ENTER键继续”
。但是,如果未使用-noexit
启动shell,则这不会阻止shell在按enter键后关闭。如果在没有参数的情况下运行该脚本,例如双击该脚本,则不会退出该脚本:
param($Work)
# restart PowerShell with -noexit, the same script, and 1
if (!$Work) {
powershell -noexit -file $MyInvocation.MyCommand.Path 1
return
}
# now the script does something
# this script just outputs this:
'I am not exiting'
你试过了吗
$host.enternestedprompt()
这将停止执行并将它们放到嵌套提示中。当他们退出该提示时,脚本将完成,窗口将关闭
"do stuff"
Pause
是的,就像命令行一样--输出:
do stuff
Press Enter to continue...:
这个小脚本末尾的while循环提示我输入命令并执行它。它与脚本的环境一起运行,因此可以检查变量的值。输入“exit”将在执行循环时终止循环
# Do something.
cd D:\temp
$current_directory = $(pwd)
dir
write-host # Just add a little space after the dir
# Stay in the shell and execute commands.
while ($TRUE) {
$cmd = Read-Host "PS $(pwd)"
if ($cmd[0] -eq '"') { iex "& $cmd" }
else { iex $cmd }
}
我相信其他人将能够分享一些改进,但这只是一个开始。注意。我介绍过,您基本上有3个选项可以防止PowerShell控制台窗口关闭
PowerShell-NoExit“C:\SomeFolder\SomeScript.ps1”
读取主机-提示“按Enter键退出”
听起来你在寻找选项1或选项3。不要恢复一个6年的线程或任何东西,但应该注意的是,任何阅读者都可以用
Stop-Process -processname regedit
如果您启用了注册表调整(全局修复),并且确实希望运行自动关闭脚本。另一种方法是使用
$null=$host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)
结合其他答案,有几个选项:
- 从命令提示符运行:
PowerShell-NoExit“Path\to\Script\Script.ps1”
- 添加到脚本末尾:
暂停
- 添加到脚本末尾:
读取主机-提示“按Enter键退出”
- 添加到脚本末尾:
$host.enternestedprompt()
- 添加到脚本末尾:
$null=host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)
noexit
改变了PowerShell.exe的初始化方式,就像cmd.exe/k
一样。一旦它以一种方式被初始化,我认为它不能被改变。我想发布这个黑客。与UAC仰角黑客相同的技术。不漂亮,但它很有效。我刚刚注意到这个问题也被标记为powershell remoting。如果所讨论的脚本是作为作业在远程系统上运行的,那么这种攻击将不起作用。用户应该如何在之后使用powershell窗口输入命令?这正是OP所说的不需要的。[咧嘴笑]
Powershell -noexit -command {
$a=1
Echo $a
} # End block
# Script ends but PowerShell windows remains.