Reputation: 361
I have a script I am using to automate WSUS processes and the last stage of it goes on to remove all old/unnecessary files/objects.
I would like to prompt 'Press 'enter' to continue with removal or any other key to stop' before the cleanup stage to give people the option to not run it.
The code I currently have at the end of the script is here:
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
Just prior to #Part2 I would like to have the prompt 'Press enter to continue or any other key to abort'
I can't seem to find a simple way to do this? everything I've seen appears to involve nesting the entire script inside of a code block which I'd rather not do. =/
Thanks!
Upvotes: 4
Views: 21856
Reputation: 29460
You can prompt the user like this:
$response = read-host "Press enter to continue or any other key (and then enter) to abort"
If the user just presses enter, then the $response
will be empty. Powershell will convert an empty string to boolean false:
$aborted = ! [bool]$response
Or you can just query for a particular character:
$response = read-host "Press a to abort, any other key to continue."
$aborted = $response -eq "a"
Upvotes: 6
Reputation: 36332
So something I keep on hand is a Show-MsgBox function to toss into scripts. That way I can show a dialog box at will with a simple command, and it has options for what buttons to show, icons to display, window title, and text in the box.
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"))}
}
That's all there is to the function, then in your case you could do something like:
If((Show-MsgBox -Title 'Confirm CleanUp' -Text 'Would you like to continue with the cleanup process?' -Button YesNo -Icon Warning) -eq 'No'){Exit}
Then it pops up with Yes and No buttons and if they click No it exits the script.
Upvotes: 6
Reputation: 675
This isn't perfect, but it will give your user a chance to escape the script. It might actually be better because it means your user won't accidentally hit the backslash button and cancel the script when they wanted to press enter.
Write-Host "Press `"Enter`" to continue or `"Ctrl-C`" to cancel"
do
{
$key = [Console]::ReadKey("noecho")
}
while($key.Key -ne "Enter")
Write-Host "Complete"
Upvotes: 2