2015-09-03 30 views
1

我有一个脚本用于自动化WSUS进程,最后一个阶段继续删除所有旧的/不必要的文件/对象。PowerShell - 提示'你想继续吗'

我想在清理阶段之前提示'按'输入'继续清除或任何其他键停止',以使人们不能运行它。

我现在有在脚本结束时的代码是在这里:

Get-WsusServer 10.1.1.25 -PortNumber 8530 | Get-WsusUpdate -Classification All -Approval Unapproved -Status FailedOrNeeded | Approve-WsusUpdate -Action Install -Target $ComputerTarget -Verbose 

Write-Host "Updates have been approved!" 
Write-Host "Preparing to clean WSUS Server of obsolete computers, updates, and content files." 

#Part2 - WSUS Server Cleanup 

##Run Cleanup Command 
Get-WsusServer $WSUS_Server -PortNumber $PortNumber | Invoke-WsusServerCleanup -CleanupObsoleteComputers -CleanupObsoleteUpdates -CleanupUnneededContentFiles 

#之前,为了第2部分我想有提示“按回车键继续或任意键退出”

我似乎无法找到一个简单的方法来做到这一点?我见过的所有东西似乎都涉及将整个脚本嵌套在我不想做的代码块中。 =/

谢谢!

+0

难道你不能只使用读主机? – zdan

+0

我可以使用像这样的:$ x = $ host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)来等待一个键被按下。我不知道如何过滤'enter'键(或任何其他键),以便继续脚本或如果按'n'或除'enter'以外的任何其他键时如何中止脚本。 – Abraxas

+0

个人而言,如果涉及到删除东西,我更喜欢弹出对话框进行确认。这对你有用吗?代码可能只是一种很长的单行代码,并且可能会取代至少一个“Write-Host”行。 – TheMadTechnician

回答

4

,您可以提示这样的用户:

$response = read-host "Press enter to continue or any other key (and then enter) to abort" 

如果用户只需按下回车,那么$response将是空的。 PowerShell的将其转换为空字符串到布尔值false:

$aborted = ! [bool]$response 

或者你也可以查询特定的字符:

$response = read-host "Press a to abort, any other key to continue." 
$aborted = $response -eq "a" 
1

这并不完美,但它会让您的用户有机会转义脚本。它可能实际上会更好,因为这意味着您的用户不会意外按下反斜杠按钮并在想要按回车时取消脚本。

Write-Host "Press `"Enter`" to continue or `"Ctrl-C`" to cancel" 
do 
{ 
$key = [Console]::ReadKey("noecho") 
} 
while($key.Key -ne "Enter") 
Write-Host "Complete" 
3

所以,这是我保持手头是一个Show-MsgBox函数折腾成脚本。这样我就可以用一个简单的命令随意地显示一个对话框,并且可以选择显示哪些按钮,要显示的图标,窗口标题和文本。

Function Show-MsgBox ($Text,$Title="",[Windows.Forms.MessageBoxButtons]$Button = "OK",[Windows.Forms.MessageBoxIcon]$Icon="Information"){ 
[Windows.Forms.MessageBox]::Show("$Text", "$Title", [Windows.Forms.MessageBoxButtons]::$Button, $Icon) | ?{(!($_ -eq "OK"))} 
} 

那就是所有的功能,然后在你的情况,你可以这样做:

If((Show-MsgBox -Title 'Confirm CleanUp' -Text 'Would you like to continue with the cleanup process?' -Button YesNo -Icon Warning) -eq 'No'){Exit} 

然后将它与有弹出和否按钮,如果他们单击否退出脚本。

+0

谢谢超级有用。非常感谢!肯定地加入到我的小但不断增长的脚本中添加:) – Abraxas

+0

我会添加 [void] [System.Reflection.Assembly] :: LoadWithPartialName(“System.Windows.Forms”)| Out-Null 函数确保它被加载并且还使用中断或继续而不是退出:-) – MrRob

+0

没有| out-Null :-) – MrRob

相关问题