如何在Powershell中在特定时间提示用户选择?

时间:2019-06-28 15:33:10

标签: powershell

我需要删除一个程序,并且需要提示特定的时间,否则它将自动选择“否”:

我需要,如果用户10秒钟不输入输入,它将选择“ N”。 这可能吗 ?

$app = "Microsoft.WindowsSoundRecorder"

$Choice = Read-Host  "Do You Want to Uninstall SoundRecoder App [YN] ?"
Switch ($Choice) {
    Y {"You Press Yes"}
    N {"You Press No"}

}

2 个答案:

答案 0 :(得分:0)

除了使用import torch torch.manual_seed(0) 之外,您还可以使用图形化Read-Host弹出方法来显示一个消息框,该消息框会在一定秒数后自动超时:

Wscript.Shell

有了该功能,就可以像这样调用它:

function Show-Popup {
    Param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNullorEmpty()]
        [string]$Message,

        [string]$Title = 'Please choose..',

        [ValidateSet('OK','OKCancel','AbortRetryIgnore','YesNoCancel','YesNo','RetryCancel')]
        [string]$Buttons='OK',

        [ValidateSet('Error','Question','Warning','Information' )]
        [string]$Icon='Information',

        [ValidateSet('First','Second','Third' )]
        [string]$DefaultButton = 'First',       # as seen from left to right

        [int]$SecondsToWait = $null
    )
    # get the numeric value for the $Buttons (0..5)
    [uint32]$typeFlags = [array]::IndexOf(@('OK','OKCancel','AbortRetryIgnore','YesNoCancel','YesNo','RetryCancel'), $Buttons)

    # add the numeric value for the $Icon (16, 32, 48, 64)
    $typeFlags += 16 * ([array]::IndexOf(@('Error','Question','Warning','Information'), $Icon) + 1)

    # add the value for the default button
    $typeFlags += 256 * ([array]::IndexOf(@('First','Second','Third','Fourth'), $DefaultButton))

    try {
        $objShell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
        # show the popup and convert the returned int value to string
        switch ($objShell.Popup($Message, $SecondsToWait, $Title, $typeFlags)) {
            1       { return 'OK ' }
            2       { return 'Cancel ' }
            3       { return 'Abort ' }
            4       { return 'Retry ' }
            5       { return 'Ignore ' }
            6       { return 'Yes ' }
            7       { return 'No' }
            default { return 'TimeOut' }  # -1
        }
    }
    catch {
        Write-Warning "Could not create Wscript.Shell object. `r`n$($_.Exception.Message)"
    }
    finally {
        if ($objShell) { 
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objShell) | Out-Null
            [System.GC]::Collect()
            [System.GC]::WaitForPendingFinalizers()
            $objShell = $null
        }
    }
}

这将显示如下:

popup

注意:我正在荷兰机上运行它,所以“是”和“否”分别翻译为“ Ja”和“ Nee”

答案 1 :(得分:0)

这是解决方案:-

[System.Reflection.Assembly]::LoadWithPartialName("microsoft.visualbasic") | Out-Null
$box = New-Object -ComObject "Wscript.shell"
$Value = $box.popup("Do You Want to Remove Adobe Reader ?" , 15 , "Please Confirm.." , 4 + 64)
switch ($Value) {
    "6" {
        Remove-Adobe
    }
    "7" {
    }
    "-1" {
    }
}