我有一个脚本用于自动化WSUS进程,最后一个阶段继续删除所有旧的/不必要的文件/对象。
我想在清理阶段之前提示'按'input'继续清除或任何其他键停止',以使人们不能运行它。
我现在在脚本末尾的代码在这里:
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
就在#Part2之前,我想要提示“按Enter键继续或者其他任何键放弃”
有一个简单的方法来做到这一点?
我所见过的所有东西似乎都涉及将整个脚本嵌套在我不想做的代码块中。 = /
另一个简单的解决scheme是使用:
Read-Host -Prompt "Press any key to continue or CTRL+C to quit"
我相信这是一个更好的解决scheme,目前接受的答案,因为敲击input键盘的要求。 我不相信击中回车将接受UI提示,除非该UI元素是焦点。
暂停脚本,直到用户按下一个键
相关的脚本行是:
Write-Host "Press enter to continue and CTRL-C to exit ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
你可以添加一个检查input,如果你真的只想要一个键继续,这个循环就是一个循环。 你也可以添加一个else来退出脚本,但是我build议只提醒用户ctrl-c会退出。 为什么编码内置的东西。
只需添加确认到您的Invoke-WsusServerCleanup命令。 它是内置的。
您可以插入一个Read-Host cmdlet,然后按照您的要求处理input值。
$userInput = Read-Host
在任何你想要PowerShell的地方,在你的代码中写入Pause 。 PowerShell将在“按Enter键继续…:”直到您按Enter 键或closuresshell / ISE 。
build立这个答案就像一个基于OP的关于如何validationinput的评论的后续附加,作为其他好的答案的补充。在正确的地方发表评论太长了。
validationinput可以用几种方法完成。 通过个人喜好,我喜欢使用switch语句来进行inputvalidation,因为我通常会发现,比起其他一些function更容易阅读和debugging,而且比以前更多样化。
同样,我更喜欢在循环中使用函数来validation失败,因为我发现代码更清洁,更可重用。 函数也有内置的参数validation的可能性,这似乎是validationvariables内容的最佳方式。
所以就像一个例子,这是一个简单的函数,当input不符合预期的时候,这个函数会自动重新提出问题。
function Get-SomeInput { $input = read-host "Please write yes or no and press Enter" switch ($input) ` { 'yes' { write-host 'You wrote yes' } 'no' { write-host 'You wrote no' } default { write-host 'You may only answer yes or no, please try again.' Get-SomeInput } } } Get-SomeInput