Batch Script to shutdown Windows - windows

I need the following. A batch script that asks me if I want to shutdown windows 7 (Y/N).. If I click "Y", then Windows 7 shuts down right away.
Please help anyone.

You will be using SET to read an answer and set to a variable. if/goto statements carry it from there.
The shutdown command changed a bit since XP, but this is what I use for 7.
#echo off
SET /P ANSWER=Did you even try Google (Y/N)?
echo You chose: %ANSWER%
if /i {%ANSWER%}=={y} (goto :yes)
if /i {%ANSWER%}=={yes} (goto :yes)
goto :no
:yes
echo You pressed yes!
shutdown /f /s /t 01
:no
echo You pressed no!
shutdown
exit /b 1
First link on Google for your search:
https://answers.yahoo.com/question/index?qid=20081005123533AALLIPA

The most common ways to use the [shutdown][1] command are:
shutdown -s — Shuts down.
shutdown -r — Restarts.
shutdown -l — Logs off.
shutdown -h — Hibernates.
Note: There is a common pitfall wherein users think -h means "help" (which it does for every other command-line program... except shutdown.exe, where it means "hibernate"). They then run shutdown -h and accidentally turn off their computers. Watch out for that.
shutdown -i — "Interactive mode". Instead of performing an action, it displays a GUI dialog.
shutdown -a — Aborts a previous shutdown command.
The commands above can be combined with these additional options:
-f — Forces programs to exit. Prevents the shutdown process from getting stuck.
-t <seconds> — Sets the time until shutdown. Use -t 0 to shutdown immediately.
-c <message> — Adds a shutdown message. The message will end up in the Event Log.
-y — Forces a "yes" answer to all shutdown queries.

Related

How to get 2 CMD windows to 'talk' to each other?

I am probably missing the right vocabulary to talk about this problem more succinctly so excuse me if I'm a little wordy here. Under Windows 10 I have a program that runs inside a CMD command prompt It's an executable called OpenSim and it has it's own extensive command set, including 'shutdown', which initiates a graceful termination of the processes therein, closes SQL connections etc, then finally closes the CMD command window. I also have a CMD .bat file that is activated by my UPS when the power goes down that will of course open it's own window, and then does some housekeeping before closing down the hardware. One thing I want the .bat file to do is to somehow insert a 'shutdown'command into the other window's process. Is that possible? If so, how? Please assume I am a total newbie at this and you won't go far wrong. Thank you.
EDIT It looks like creating a file to flag the closedown event taking place is the only (and I guess rather primitive) way to do this. So, building on what others have said in stackoverflow, I have the following now. When I run it to test it waits - it doesn't. It runs right through to the end, running 'shutdown', even though the UPSFLAG.TXT file does not exist. What's going wrong?
echo Waiting for UPS Power Down Signal.
echo =================================
#ECHO OFF
SET LookForFile="C:\Opensim OSGrid\UPSFLAG.TXT"
:CheckForFile
IF EXIST %LookForFile% GOTO FoundIt
REM If we get here, the file is not found.
REM Wait 10 seconds and then recheck.
REM If no delay is needed, comment/remove the timeout line.
TIMEOUT /T 10 >nul
GOTO CheckForFile
:FoundIt
ECHO Found: %LookForFile%
rem Tidy up
del "C:\Opensim OSGrid\UPSFLAG.TXT"
shutdown
Adding double quote after the = will save your variable as that "C:\Opensim OSGrid\UPSFLAG.TXT" which you do not want. rather you want to store it as C:\Opensim OSGrid\UPSFLAG.TXT so move the quote to before lookforfile.
Also, you created a variable for the file, so you might as well use it in the delete.
Finally, as a safety measure, always put an exit after a goto. That will ensure the system exists should there be a problem in the script and you can make sure you do not delete files or shutdown the system when it was not planned for.
echo Waiting for UPS Power Down Signal.
echo =================================
#ECHO OFF
SET "LookForFile=C:\Opensim OSGrid\UPSFLAG.TXT"
:CheckForFile
IF EXIST "%LookForFile%" GOTO FoundIt
REM If we get here, the file is not found.
REM Wait 10 seconds and then recheck.
REM If no delay is needed, comment/remove the timeout line.
TIMEOUT /T 10 >nul
GOTO CheckForFile
exit
:FoundIt
ECHO Found: %LookForFile%
rem Tidy up
del "%LookForFile"
shutdown

Batch file to commit changes to Embedded XP and then restart pc

I would like to create a batch file to run a cmd command to commit changes to a windows embedded pc from a USB drive and restart the PC to make the changes active.
The cmd line I use is:
ewfmgr -commit c:
But I need to open the cmd prompt and run the command then once it has run, restart the PC
This is what worked
#echo OFF
:reboot
c:\windows\system32\ewfmgr.exe C: -commit
echo Rebooting...Please Wait
c:\windows\system32\xpepm.exe -restart
pause
shutdown /? could give some hints. Then your batch file might look as follows:
ewfmgr -commit c:
shutdown /r
To ensure batch wait until ewfmgr command ends, use
start "" /W ewfmgr -commit c:
shutdown /r
With the /W or /WAIT switch, the start command will start application and wait for it to terminate. More info on start command.
To give a some kind of wait after the commit command so that it can run and finish its task, e.g. for a delay of 30 seconds:
add timeout /T 30 /nobreak>nul line before shutdown /r, and/or
use shutdown with /t xxx switch (this sets the time-out period
before shutdown to xxx seconds), i.e. shutdown /r /t 30
A workaround if timeout command is not recognized: PING -n 31 127.0.0.1>nul
Create a new file with the .bat extension. Open it in your preferred text editor and enter the commands you want to be run, and save the file. The commands that JosefZ wrote would probably do the job perfectly.

How to close Windows console automatically (send CTRL+C to console programatically)?

I have two windows batch scripts, script1.bat and script2.bat. script2.bat is launched from script1.bat.
script1.bat:
...
start call script2.bat
...
script2.bat has to be closed when user closes script1.bat's console (in another words, script2.bat and its console should be closed automatically when script1.bat is closed). But script2.bat should not be killed, It should be terminated because script2.bat has to release database connection. I mean unix signal teminology by using kill and terminate words. So scrip2.bat should not be killed immediately, it should be terminated in way that allows the process to perform nice termination releasing resources and saving state if appropriate.
I made it for unix system and I resolved it as following.
script1.sh:
...
sh script2.sh > /dev/null 2>&1 &
script2_pid="$!"
trap 'kill -15 $script2_pid' EXIT HUP TERM INT KILL
...
How to make it on Windows?
====EDIT====
I think that my question is not entirely clear for everyone so I would like to clarify it.
I have java application which connects to JBoss application server. It is tested now and I need to launch both in very convenient way. I prepared batch script (script1.bat)which starts both, client application and JBoss application. This script also do another things like setting environment variables. So script2.bat is a Jboss standalone.bat file in fact. I wouldn't like to edit this file.
script1.bat is my script, it sets environment variables, start JBoss and start my java application.
My script (script1.bat):
...
set environment variable
...
REM start jboss
start standalone.bat
REM start my java application
java ...
When user closes Java application, JBoss should also be closed. I need it only for tester's convenient and I know that in production environmnet it should work in another way.
I don't know how to terminate JBoss automatically after user closes my java client application. JBoss connects to H2 database and creates lock on it so if JBoss will be killed immediately then database lock is still there. If JBoss process receives CTRL+C it terminates properly (removes database lock). I want to make it automatically, After user closes java client application, JBoss has to be closed as it receives CTRL+C.
I have no idea how to do it on Windows. But I did it on linux and I added my code to this question.
Sorry, but your script makes no sense. start call script2.bat?? The combination of start and call is nonsense. You use either one or the other but not both.
Further I have to disappiont you. There is no way to close a console but keep the code running. You can't even start a hidden console in Windows. Closing the console will instantly stop the execution of the code.
EDIT:
Now I understand what you are asking. Start your first script using
start "somename" script1.bat
This will start script1 in a console with "somename" as window title.
In the second script you can use this:
:WORKING
REM Do some stuff here
REM and here
REM and here
FOR /f "tokens=*" %%A IN ('tasklist^ /v^| findstr /i /c:"somename"') DO GOTO WORKING
REM shutdown part
REM close db connections
REM exit script2
This part will check if the a console with "somename" in the title is running and if yes reenter the loop. At the end of the loop it alway checks whether script1 is still active. As soon as it's not found the code goes on to the shutdown part.
If you only want to wait for script1 to terminate you can use PING -n 5 127.0.0.1 > NUL as a 5 (or longer, just replace the 5 ^^) second timeout to avoid busy-waiting:
:WORKING
PING -n 5 127.0.0.1 > NUL
FOR /f "tokens=*" %%A IN ('tasklist^ /v^| findstr /i /c:"somename"') DO GOTO WORKING
REM shutdown part
REM close db connections etc.
REM exit script2
If CLI is enabled in JBoss then JBoss can be shutdowned by CLI. Following batch shows how to shutdown JBoss
...
set environment variable
...
REM start jboss
start "UNIQUE_NAME" path_to_JBoss\bin\standalone.bat -c standalone.xml
REM start java application
java ...
REM shutdown JBoss by CLI
call path_to_JBoss\bin\jboss-cli.bat --connect ":shutdown"
REM it is just in case. If CLI did not shutdown JBoss, then following line kills JBoss without release of resource.
FOR /f "TOKENS=1,2,*" %%a IN ('tasklist^ /FI "WINDOWTITLE eq UNIQUE_NAME*" /nh') DO taskkill /pid %%b

Batch - Reboot computer if a batch file ends

Essentially we have 2 batch files, one which is the "wrapper" if you will, calling another batch file so it starts as /min (minimized). This batch file then ends once it has launched the 2nd batch file.
This contains a loop, which keeps spawning an RDP session after it is closed.
The problem is, if the user ALT-TABs and closes the batch, they are just left with an empty desktop (as we task kill explorer). Is there a way of force rebooting the machine if that batch loop ends?
Thanks!
There is a standard cmd command:
shutdown /r
Usage: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/f]
[/m \\computer][/t xxx][/d [p|u:]xx:yy [/c "comment"]]
No args Display help. This is the same as typing /?.
/? Display help. This is the same as not typing any options.
/i Display the graphical user interface (GUI).
This must be the first option.
/l Log off. This cannot be used with /m or /d options.
/s Shutdown the computer.
/r Full shutdown and restart the computer.
/g Full shutdown and restart the computer. After the system is
rebooted, restart any registered applications.
/a Abort a system shutdown.
This can only be used during the time-out period.
/p Turn off the local computer with no time-out or warning.
Can be used with /d and /f options.
/h Hibernate the local computer.
Can be used with the /f option.
/hybrid Performs a shutdown of the computer and prepares it for fast startup.
Must be used with /s option.
/e Document the reason for an unexpected shutdown of a computer.
/o Go to the advanced boot options menu and restart the computer.
Must be used with /r option.
/m \\computer Specify the target computer.
/t xxx Set the time-out period before shutdown to xxx seconds.
The valid range is 0-315360000 (10 years), with a default of 30.
If the timeout period is greater than 0, the /f parameter is
implied.
/c "comment" Comment on the reason for the restart or shutdown.
Maximum of 512 characters allowed.
/f Force running applications to close without forewarning users.
The /f parameter is implied when a value greater than 0 is
specified for the /t parameter.
/d [p|u:]xx:yy Provide the reason for the restart or shutdown.
p indicates that the restart or shutdown is planned.
u indicates that the reason is user defined.
If neither p nor u is specified the restart or shutdown is
unplanned.
xx is the major reason number (positive integer less than 256).
yy is the minor reason number (positive integer less than 65536).
My suggestions:
Do you really need batch to be visible (minimized) or can it be hidden?
If it can be hidden, just use VBScript to launch it hidden:
With CreateObject("W"&"Script.Shell")
.Run "LongRun.bat", 0
End With
If you really need batch to be shown, you could make a hidden script which will wait for batch to terminate and reboot.
Step 1: Launch script hidden (Start.vbs):
Set WsShell = CreateObject("W"&"Script.Shell")
WsShell.Run "Hidden.vbs", 0
Step 2: Hidden.vbs will launch batch and wait it to return:
'This script is supposed to start hidden!
Set WsShell = CreateObject("W"&"Script.Shell")
WsShell.Run "LongRun.bat", 7, True
'WsShell.Run "REBOOT.EXE ..." 'Must remove comment and complete command line
MsgBox "Rebooting..."
Now LongRun.bat is running, Hidden.vbs also (but not visible).
If somehow LongRun.bat is terminated, Hidden.vbs will continue its execution and reboot.
(WScript.Shell.Run documentation)
EDIT: Notice "W"&"Script.Shell" is same as "WScript.Shell" but StackOverflow doesn't allow me to write it!

Windows shutdown-script: unexpected behavior

I wrote a little script which would prompt me for an input, save that input to a text file and shutdown the PC afterwards.
This is what the code looks like:
#ECHO OFF
set /p input=Insert text:
echo %DATE%: %input% >> text.txt
echo The system will shutdown...
shutdown -s -f -t 3
When I execute the batch, it prompts me and saves the input correctly, but after displaying The system will shutdown... it doesn't shut down, instead it starts over again promting me for input.
Does anyone know what causes this behavior?
May I ask the name of your batch file? If it is named shutdown.bat it is likely getting called again rather than executing the shutdown command. Try renaming your batch file if you would please.
The only thing I can see that might be wrong is that you are using -'s for the shutdown switches, which is correct in (I think) XP, but in Win7 (not sure about Vista) shutdown /? says to use /'s.
shutdown /s /f /t 3

Resources