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

8

u/Gohan472 Feb 02 '23

You can always ask ChatGPT

-12

u/MrInkognitus Feb 02 '23

Yes, and the code is good, but I can’t get it work the way I wont it to

2

u/Gohan472 Feb 02 '23

Here was my prompt for ChatGPT -- "Create a powershell script that will tell the user the "system is shutting down in 10 mins", provide the user with the option of OK or Cancel. If the user presses cancel, the script will stop. If the user Presses OK or does nothing, then the system should shutdown during the 10 min countdown"

This is what ChatGPT provided me with

$result = [System.Windows.Forms.MessageBox]::Show("System is shutting down in 10 minutes. Do you want to cancel?", "System Shutdown", [System.Windows.Forms.MessageBoxButtons]::OKCancel)

if ($result -eq [System.Windows.Forms.DialogResult]::Cancel) {

Write-Output "Shutdown cancelled by user."

} else {

Start-Sleep -Seconds 600

Stop-Computer

}

We are also missing a crucial component in this script to make it function properly --
Add-Type -AssemblyName System.Windows.Forms

So, your final output should be

Add-Type -AssemblyName System.Windows.Forms

$result = [System.Windows.Forms.MessageBox]::Show("System is shutting down in 10 minutes. Do you want to cancel?", "System Shutdown", [System.Windows.Forms.MessageBoxButtons]::OKCancel)

if ($result -eq [System.Windows.Forms.DialogResult]::Cancel) {

Write-Output "Shutdown cancelled by user."

} else {

Start-Sleep -Seconds 600

Stop-Computer

}

1

u/MrInkognitus Feb 03 '23

Yes, this code is identical to mine, but it asks for user interaction to start the counting, I need the counting to start as soon as the program runs, and if no one cancels after 10 minutes the computer shuts down.

1

u/PotentialBid1423 Feb 03 '23

Right but then you can ask it to re-write it so it’s not expecting input. You can push it far if you just keep pushing it. The biggest drawbacks I’ve seen is the fact that it will make up cmdlets or use an improper syntax. Then you research why after you push it enough and this expedited learning the language in my opinion. Much more practical learning this way but base knowledge takes time.

1

u/EVASIVEroot Feb 02 '23

I was going to mention the Add-Type for forms then bam!

I might need to take a look at this chatgpt thing

I always pipe to | Out-Null after just in case.

4

u/Gohan472 Feb 02 '23

Right on! ChatGPT is pretty good. If you encounter errors when trying to run things, you can reply back with "I received this error when running the script or code or whatever" and it will analyze and then correct the issue. For the most part :)

29

u/bstevens615 Feb 02 '23

What have you tried? You will find most users of r/PowerShell will be happy to help you fix your code. But very few will write it for you from scratch.

1

u/Revolutionary_Lie539 Feb 03 '23

Can you do my work for me?

4

u/raysfandan Feb 02 '23
# Pop up window to confirm shutdown
$ConfirmBox = [System.Windows.MessageBox]::Show("Your  computer will shut down in 10 minutes. Do you want to cancel the shutdown?", "Shutdown Confirmation",  [System.Windows.MessageBoxButton]::YesNo)

# If user clicked "No", proceed with shutdown
if ($ConfirmBox -eq "No") {
  Start-Sleep -Seconds 600
  Stop-Computer
}

3

u/SMFCAU Feb 02 '23

Need to start the timer outside of your if statement, otherwise it doesn't catch the prompt being ignored completely (EG - computer unattented).

-10

u/MrInkognitus Feb 02 '23

This code doesn’t work. Is identical to mine code, but de counter only start when I click on cancel button, but I need the countdown start immediately when the program start, and the program stop if I click on cancel button.

13

u/BlackV Feb 02 '23

how would we know, you didn't post your code.....

12

u/[deleted] Feb 02 '23

Come on! Google! Read docs! Then if you failes, publish your script here and we can help, give it a try first before asking

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

5

u/landob Feb 03 '23

At the rate these show up think we should just make a new subreddit called "/r/powershellrequest"" and they can tip the best one.

1

u/nawadsama Feb 03 '23
$main = New-Object System.Windows.Forms.Form
$main.ClientSize = '220,200'
$main.MinimizeBox = $false
$main.MaximizeBox = $false
$main.FormBorderStyle = [System.Windows.Forms.BorderStyle]::None
$main.Text = 'Tajm'
$main.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$label = New-Object System.Windows.Forms.Label
$label.Size = '190,30'
$label.Location = '10,10'
$label.Text = 'Ile minut?'
$font = New-Object System.Drawing.Font("Arial", 23)
$label.Font = $font
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.Size = '50,100'
$textbox.Location = '10,70'
$button = New-Object System.Windows.Forms.Button
$button.Size = '50,50'
$button.Location = '10,120'
$button.Text = 'GO'
$button.Add_Click({
$timer.Start()
$textbox.Visible =$false
$button.Visible = $false
$label.Visible = $false
$script:1 = New-TimeSpan -minutes ([int]$textbox.Text)
$label2.Visible = $true
$label2.Text = $1.ToString("mm\:ss")
$button2.Location = [System.Drawing.Point]::new(10,100)
$button2.Size = [System.Drawing.Size]::new(200,90)
})
$timer = New-Object System.Windows.Forms.Timer
$timer.Enabled = $false
$timer.Interval = '1000'
$second = New-TimeSpan -Seconds 1
$timer.Add_Tick({
$script:1 = $1.Subtract($second)
$label2.Text = $1.ToString("mm\:ss")
if($script:1.TotalSeconds -le 0){$timer.Stop(); $timer.Dispose(); [System.Windows.Forms.Application]::SetSuspendState("Hibernate", $true, $false); $main.Close(); $main.Dispose()}
})
$label2 = New-Object System.Windows.Forms.Label
$label2.Size = '210,100'
$label2.Location = '10,10'
$label2.Text = $1
$label2.ForeColor = [System.Drawing.Color]::Crimson
$font = New-Object System.Drawing.Font("Arial", 23, [System.Drawing.FontStyle]::Underline)
$label2.Font = $font
$label2.TextAlign = 'MiddleCenter'
$label2.Visible = $false
$button2 = [System.Windows.Forms.Button]::new()
$button2.Size = [System.Drawing.Size]::new(50,50)
$button2.Location = [System.Drawing.Point]::new(60,120)
$button2.Text = 'Cancel'
$button2.Add_Click({
$timer.Stop()
$main.Close()
})
$main.Controls.Add($textbox)
$main.Controls.Add($button)
$main.Controls.Add($button2)
$main.Controls.Add($label)
$main.Controls.Add($label2)
$main.ShowDialog()

This is a part of a bigger script I use on a regular basis. You can tweak some parts and it should do what you want.

1

u/MrInkognitus Feb 03 '23

The code is interesting, but how do I change it so that it doesn't ask for the time, and immediately starts counting 10 min as soon as I run the program? And just give the user the option to cancel the shutdown?

1

u/nawadsama Feb 03 '23
$main = New-Object System.Windows.Forms.Form

$main.ClientSize = '220,200' $main.MinimizeBox = $false $main.MaximizeBox = $false $main.FormBorderStyle = [System.Windows.Forms.BorderStyle]::None $main.Text = 'Tajm' $main.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen $timer = New-Object System.Windows.Forms.Timer $timer.Enabled = $false $timer.Interval = '1000' $second = New-TimeSpan -Seconds 1 $timer.Start() $1 = New-TimeSpan -minutes 10 $timer.Add_Tick({ $script:1 = $1.Subtract($second) $label2.Text = $1.ToString("mm:ss") if($script:1.TotalSeconds -le 0) {$timer.Stop() $timer.Dispose() Stop-Computer $main.Close() $main.Dispose()} }) $label2 = New-Object System.Windows.Forms.Label $label2.Size = '210,100' $label2.Location = '10,10' $label2.Text = $1 $label2.ForeColor = [System.Drawing.Color]::Crimson $font = New-Object System.Drawing.Font("Arial", 23, [System.Drawing.FontStyle]::Underline) $label2.Font = $font $label2.TextAlign = 'MiddleCenter' $label2.Visible = $true $button2 = [System.Windows.Forms.Button]::new() $button2.Size = [System.Drawing.Size]::new(50,50) $button2.Location = [System.Drawing.Point]::new(60,120) $button2.Text = 'Cancel' $button2.Add_Click({ $timer.Stop() $main.Close() }) $main.Controls.Add($button2) $main.Controls.Add($label2) $main.ShowDialog()

Like this

2

u/hackoofr Feb 02 '23 edited Feb 02 '23

This can also be done in VBScript, but at least show us what you have tried as code until now !

2

u/Akimotos Feb 02 '23

vbscript? <grin>

-1

u/hackoofr Feb 02 '23

Here is the VBScript that can do the trick :

 Option Explicit
 Dim Msg,objShell, intTime, intCancel
 Msg = "Your computer will shut down in 10 minutes. Press OK to continue or Cancel to stop the shutdown"
 intTime = 600
 Set objShell = CreateObject("WScript.Shell")
 intCancel = objShell.Popup(Msg, intTime, "Shutdown in Progress",vbOKCancel+vbExclamation+vbSystemModal)
 If intCancel = vbOK Then
     objShell.Run "shutdown /s /t " & intTime, 0, True
 End If

3

u/Akimotos Feb 02 '23

I would never go back using VBScript.
But it's a solution to a problem.

1

u/BruhahGand Feb 02 '23

Something similar that you can start from.

0

u/[deleted] Feb 02 '23

[deleted]

1

u/MrInkognitus Feb 03 '23

Good Morning,
Unfortunately that code is not working.
The error it gives is:

At line:9 char:231

+ ... nt(100,150) $cancel.Add_Click({ $timer.Enabled = $false $form.Close() ...

+ ~~~~~

Unexpected token '$form' in expression or statement.

At line:13 char:98

+ ... omputer will shut down in $($timer.Interval/1000) seconds" if ($timer ...

+ ~~

Unexpected token 'if' in expression or statement.

+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

+ FullyQualifiedErrorId : UnexpectedToken

I have no programming experience, but I need a script like this at work.

-5

u/MrInkognitus Feb 02 '23

Thanks I test the code tomorrow and tell us the result