我知道PowerShell有一个名为-noexit
的小开关。
是否有不使用该开关而保持在shell中的方法?
换句话说,我想要一个执行命令后保持shell打开的脚本命令。
我知道PowerShell有一个名为-noexit
的小开关。
是否有不使用该开关而保持在shell中的方法?
换句话说,我想要一个执行命令后保持shell打开的脚本命令。
您基本上有3个选项来防止PowerShell控制台窗口关闭,我在我的博客文章中详细描述。
PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Read-Host -Prompt "按Enter键退出"
请查看我的博客以获取有关要修改哪些注册表键的更多信息。
听起来您正在寻找选项#1或#3。
如果您没有输入参数就运行这个脚本(比如双击它),它将不会退出:
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...:
如果没有使用-noexit
命令调用,我不知道在脚本中可以运行哪个命令可以防止shell退出。
通常,如果我不希望shell关闭,我会在结尾处使用Read-Host "Press ENTER to continue"
。但是,如果没有使用-noexit
启动shell,则此方法无法防止shell在按下enter键后关闭。
noexit
改变了 PowerShell.exe 的初始化方式,就像 cmd.exe /k
一样。一旦它被初始化成某种方式,我认为它就无法改变了。 - Andy Arismendi这个简单的脚本末尾的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 }
}
我相信其他人也能分享一些改进意见,但这只是一个开始。敬礼。
PowerShell -File c:\myscript.ps1 -NoExit
另一种方法是使用$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
。
结合其他答案,有几个选项:
PowerShell -NoExit "Path\to\Script\script.ps1"
pause
read-Host -Prompt "Press Enter to exit"
$host.enternestedprompt()
$null = host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Powershell -noexit -command {
$a=1
Echo $a
} # End block
# Script ends but PowerShell windows remains.
Stop-Process -processname regedit