How do I shutdown, restart, or log off Windows via a bat file?

The most common ways to use the shutdown 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 … Read more

Batch file to delete files older than N days

Enjoy: forfiles -p “C:\what\ever” -s -m *.* -d <number of days> -c “cmd /c del @path” See forfiles documentation for more details. For more goodies, refer to An A-Z Index of the Windows XP command line. If you don’t have forfiles installed on your machine, copy it from any Windows Server 2003 to your Windows XP machine at %WinDir%\system32\. … Read more

How to sleep for five seconds in a batch file/cmd [duplicate]

I’m very surprised no one has mentioned: C:\> timeout 5 N.B. Please note however (thanks Dan!) that timeout 5 means: Sleep anywhere between 4 and 5 seconds This can be verified empirically by putting the following into a batch file, running it repeatedly and calculating the time differences between the first and second echos: @echo … Read more

Windows batch files: .bat vs .cmd?

From this news group posting by Mark Zbikowski himself: The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors. In other words, if ERRORLEVEL is set to non-0 and then you run one … Read more

How to “comment-out” (add comment) in a batch/cmd?

Use :: or REM :: commenttttttttttt REM commenttttttttttt BUT (as people noted): if they are not in the beginning of line, then add & character: your commands here & :: commenttttttttttt Inside nested parts (IF/ELSE, FOR loops, etc…) :: should be followed with normal line, otherwise it gives error (use REM there). :: may also … Read more

What does %~dp0 mean, and how does it work?

Calling for /? in the command-line gives help about this syntax (which can be used outside FOR, too, this is just the place where help can be found). In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax: %~I – expands %I removing any surrounding quotes (“) … Read more

File not found.