2015-09-03 62 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

相關問題