Yes, I know, everyone says “Batch is dead, man. Dead”. As in “deeeeeeaaaaad, maaaaaaaan.” Well, it may be “dead, man” but it’s still used in a lot of places for a lot of jobs. Let’s face it, it’s quick and simple. At least when used as it was intended. The problems usually arise when we try to push batch script into doing more than it was really designed to do. That’s really the dilemma admins and coders face over time: When to put aside one tool for another, based on the task at-hand.
Sorry for the long diatribe, but just because you can do a lot with stuff like this…
FOR /F "tokens=n,m* delims=ccc" %%A IN (... blah blah)
…doesn’t mean that nesting this twenty times is better than doing it in fewer lines with some other language. It’s kind of like the wrench and hammer analogy: Just because you can pound nails with a wrench doesn’t mean it’s the best tool for it. Then again, if you enjoy beating nails with wrenches, have at it.
Anyhow, a batch script is handy for launching other things, even scripts. It’s especially handy for grouping multiple such things into a sequence of tasks; hence the “batch” moniker. Whoa! Shocker. So, long-story-short, it’s pretty common to find it necessary to launch scripts using “Run as administrator” in order for the subsequent tasks to operate. Even launching things like Sysinternals’ PsExec using /s require that the initiating context be an elevated one. That last sentence was awkward to write. I need to work on my writing of course.
So, this chunk of code relies on dism.exe being accessible (and in the default path environment). It simply calls to dism.exe without any arguments so it will open-and-shut without any jaw-flapping or lip-smacking. If it’s invoked without an elevated rights context, it returns an error (in CMD shell, it returns 740, in case you care). Otherwise it closes with 0 (zero), which is good. Zero is often good, except when it’s my bank account.
@echo off dism >nul IF %ERRORLEVEL% EQU 0 ( echo Running in elevated context. ) ELSE ( echo This script has to be launched using Run as Administrator )
Sexy, huh? Were you expecting 50 lines of code? I’m sure there are other ways to do this, which are probably fine, but this also works. Copy and paste it into a .bat script and try it out. Cheers! Enjoy. 🙂