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

Show parent comments

-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.