Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Prompt user then expire prompt after xx seconds

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."}   
like image 905
Ernest Vannorsdell Avatar asked Sep 08 '14 16:09

Ernest Vannorsdell


1 Answers

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
like image 178
Noah Sparks Avatar answered Oct 07 '22 20:10

Noah Sparks