单击弹出框上的取消时如何停止脚本?

时间:2017-10-11 05:19:59

标签: powershell

当用户在某个弹出框上单击“取消”时,我需要能够停止我的脚本。部分脚本如下:

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -ne "Microsoft Windows 10 *"){

   $wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("This computer is currently running $OS. To continue with the 
script click OK, otherwise click Cancel.",0,"Windows 10 
Notification",0x1)

}

这是用户必须决定终止脚本进度或继续的地方。我需要能够在用户单击“确定”时继续运行脚本,但在单击“取消”时停止脚本继续运行。

2 个答案:

答案 0 :(得分:1)

您可以捕获变量中的弹出答案,并使用if-statementBreak停止脚本。试试这个:

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -ne "Microsoft Windows 10 *"){

    $wshell = New-Object -ComObject Wscript.Shell
    $answer = $wshell.Popup("This computer is currently running $OS. To continue with the 
    script click OK, otherwise click Cancel.",0,"Windows 10 
    Notification",0x1)

    if($answer -eq 2){Break}

}

$answer显示 1 表示确定, 2 表示取消

答案 1 :(得分:0)

我更喜欢使用Windows窗体并相应地更新脚本。您可以找到更多示例here

我还更改了if条件,因为你在哪里检查变量$OS是否完全 "Microsoft Windows 10 *";使用-notlike代替-ne来检查开始是否开始

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -notlike "Microsoft Windows 10 *") {
    $PopupTitle = "Windows 10 Notification"
    $PopupMessage = "This computer is currently running $OS. To continue with the script click OK, otherwise click Cancel."
    $PopupOptions = "OkCancel"
    $PopupAnswer = [System.Windows.Forms.MessageBox]::Show($PopupMessage,$PopupTitle,$PopupOptions,[System.Windows.Forms.MessageBoxIcon]::Exclamation)

    if ($PopupAnswer -eq "Cancel") {
        Break
    }
}