How to get a timer in a Powershell messagebox?

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

I'm trying to display a timer in my message box that I created with PS Forms. I would like something like that:

" Your PC will be shutdown in 10 sec" after 1 sec.

"Your PC will be shutdown in 9 sec"

"Your PC will be shutdown in 8 sec" and so on.

Hope you can help me.

回答1:

I don't see a way of refreshing the text in a message box. If I had to do this I would probably pop up another form with a label and use a timer that refreshes the text of the label on each tick.

Here is a code example to use a potential starting point:

Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $Form = New-Object system.Windows.Forms.Form $script:Label = New-Object System.Windows.Forms.Label $script:Label.AutoSize = $true $script:Form.Controls.Add($Label) $Timer = New-Object System.Windows.Forms.Timer $Timer.Interval = 1000 $script:CountDown = 60 $Timer.add_Tick(     {         $script:Label.Text = "Your system will reboot in $CountDown seconds"         $script:CountDown--     } ) $script:Timer.Start() $script:Form.ShowDialog() 

You will need to expand to meet your needs such as conditional logic to do whatever action you want (e.g., reboot) when the count down reaches 0, perhaps add a button for aborting, etc.



回答2:

There's PopUp Method from Windows Script Host, that enables you to set a time to live for the PopUp. I don't think that there is a way no refresh a message box from PowerShell (don't quote me on that). Two lines of the code came from here.

Not sure if it's this that you want, but this works (crude solution):

$timer = New-Object System.Timers.Timer $timer.AutoReset = $true #resets itself $timer.Interval = 1000 #ms $initial_time = Get-Date $end_time = $initial_time.AddSeconds(12) ## don't know why, but it needs 2 more seconds to show right  # create windows script host $wshell = New-Object -ComObject Wscript.Shell # add end_time variable so it's accessible from within the job $wshell | Add-Member -MemberType NoteProperty -Name endTime -Value $end_time  Register-ObjectEvent -SourceIdentifier "PopUp Timer" -InputObject $timer -EventName Elapsed -Action {     $endTime = [DateTime]$event.MessageData.endTime     $time_left = $endTime.Subtract((Get-Date)).Seconds      if($time_left -le 0){         $timer.Stop()         Stop-Job -Name * -ErrorAction SilentlyContinue         Remove-Job -Name * -ErrorAction SilentlyContinue         #other code         # logoff user?     }     $event.MessageData.Popup("Your PC will be shutdown in $time_left sec",1,"Message Box Title",64) } -MessageData $wshell  $timer.Start() 

EDIT : The solution presented by @JonDechiro is much cleaner than mine and more apropriate for what OP asked.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!