Powershell - Prompt user then expire prompt after xx seconds
Asked Answered
R

1

9

I am trying to display a promp for user action and if no action is taken have the prompt close and teh script continue on. here is my command prompt dialog configuraiton


$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",""
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",""
$cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel",""
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no,$cancel)
$caption = "Caption message here"
$dialogmessage = ("Do you want to do something?:`n")

$timer = #set some value
#While the value is grater than zero keep the prompt open

while($timer -gt 0)
{
    $result = $Host.UI.PromptForChoice($caption,$dialogmessage,$choices,0)

    if($result -eq 0){Write-Host "Yes was selected"}

    if($result -eq 1){Write-Host "No was selected"}

    if($result -eq 2){Write-Host "Canceled by user.";exit}
 }

I have looked up and down the internet I have seen this implemented in C# but for the life of me i cannot determine the best approach for powershell. I would appreciate any help.

Thank you

Edit: Thank you Noah, here is the updated code, it is even more compact too!

        $prompt = new-object -comobject wscript.shell 
        $answer = $prompt.popup("Do you want to do something?`n",5,"title",3)              
        if($answer -eq 6) {Write-Host "Yes was selected"}
        if($answer -eq 7) {Write-Host "No was selected"}
        if($answer -eq -1) {Write-Host "Timed out"}
        if($answer -eq 2) {Write-Host "Canceled by user."}   
Reddish answered 8/9, 2014 at 16:55 Comment(0)
S
11

Here you go...dug this out of one of my old scripts

#Value  Description   
#0 Show OK button. 
#1 Show OK and Cancel buttons. 
#2 Show Abort, Retry, and Ignore buttons. 
#3 Show Yes, No, and Cancel buttons. 
#4 Show Yes and No buttons. 
#5 Show Retry and Cancel buttons. 
#http://msdn.microsoft.com/en-us/library/x83z1d9f(v=vs.84).aspx

$a = new-object -comobject wscript.shell 
$intAnswer = $a.popup("Question?",2,"Title",4) #first number is timeout, second is display.

#7 = no , 6 = yes, -1 = timeout
Seline answered 8/9, 2014 at 17:37 Comment(2)
Wow I never though to use the wscript.shell comobject. Thank you Noah!Reddish
For me this does not work with values over 19 seconds: #67330665Ty

© 2022 - 2024 — McMap. All rights reserved.