Search code examples
powershellcmdshutdownreboot

Shutdown/restart command using a variable in powershell


I am working on a GUI reboot modul in a tool of mine. I want to use the command prompt "shutdown" command line for this. Its purpose is to replace the "shutdown -i" on multiple servers and then I can ping them automatically to check if the reboot was succesfull.

In CMD the command line looks like this:

shutdown /r /t 30 /m \\server /c "reboot reason"

In my script I will ask for the:

  • reason = $comment
  • time = $time (the value and also in a checkbox if it is required or not)
  • server name = $server

I will test with a few "if"s the time option, is it checked or not and that the reboot reason is not empty and then add all of them to a variable:

$reboot = "/r /t " + $time + "/m \\" + $server + "/c " + $comment

and then use the variable in the command in powershell:

& shutdown $reboot

My question is will this work? Did anyone use it like this? Or there is a better way to do it? I can't test it for a few days because I don't have any servers right now on the network that I can reboot feely.


Solution

  • It should work, yes. I would also recommend using an array for the parameters to keep it clean.

    $time = 120
    $server = "mycomputer"
    $comment = "this is my comment."
    $reboot = @("/r", "/t", $time, "/m", "\\$server", "/c", $comment)
    
    & shutdown $reboot
    

    Or you could try doing it using WMI (untested):

    $time = 120
    $comment = "this is my comment."
    $server = "mycomputer"
    
    Invoke-WmiMethod -ComputerName $server -Class Win32_OperatingSystem -Name Win32ShutdownTracker -ArgumentList @($time, $comment, 0, 2)