r/PowerShell • • Feb 02 '23

Question Powershell script to shutdown a computer

Hi, I could use your help. I am trying to create a Powershell script that allows me to shutdown a computer after 10 minutes. Once I run the script I wanted a window to pop up telling the user that the computer would shut down in 10 minutes, and if he wanted to cancel. If he hit the cancel button the script would stop, if he didn't touch the computer after 10 minutes it would shutdown. Can you help me create a script like this? Thanks.

0 Upvotes

28 comments sorted by

View all comments

1

u/MrInkognitus Feb 03 '23

At this point, and reading some documentation, I came up with this code:
$countdown = 10
$message = "Deseja cancelar?"
$title = "Shutdown"
$choice = [System.Windows.MessageBox]::Show($message, $title, [System.Windows.MessageBoxButton]::OKCancel) 
if ($choice -eq [System.Windows.MessageBoxResult]::Cancel) {
    Write-Host "Shutdown cancelado user."
}
else {
    Write-Host "Iniciando contagem decrescente..."
    while ($countdown -gt 0) {
        Write-Host "Tempo restante: $countdown segundos."
        Start-Sleep -Seconds 1
        $countdown--
    }
    Write-Host "Desligando o computador."
    Stop-Computer
}

If I press the cancel button, the program stops, so far so good, that's what I want.

But the problem is that I need the counting to start as soon as the program starts, and to turn off after 10 minutes without user interaction. The only thing the user needs to interact with is if he wants to stop the shutdown.

Thanks