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/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 :)