5 IF Statements to Use for Smarter Windows Batch Scripts

If you do a lot of work in Windows batch files, the IF statement offers a very powerful way to add flexibility to your scripts.  computer science computer science computer science computer science computer science
In this article you’re going to learn about the five main types of IF statements you can use in a Windows batch file, how the correct syntax looks, and a realistic example for each. computer science computer science computer science
If you’re ready to start scripting, let’s get started! computer science computer science computer science computer science computer science computer science computer science computer science computer science computer science

1. Compare Values

One of the basic things you’ll usually need to do in a batch script is compare two valuesand follow a different course of action depending on the comparison. computer science computer science computer science computer science
For example, let’s say you wanted to write a batch script that checks your computer’s hard drive size daily. If it’s below 3 GB you want to get an email report that says, “Hard Drive Space Too Low.” computer science
To create a script that compares the current free hard drive space to your limit, you’d create the following batch script and save it as a .bat file. computer science computer science computer science computer science 

@echo off
set DriveLimit=300000000
for /f "usebackq delims== tokens=2" %%x in (`wmic logicaldisk where
"DeviceID='C:'" get FreeSpace /format:value`) do set FreeSpace=%%x
Echo FreeSpace="%FreeSpace%"
Echo Limit="%DriveLimit%"
If %FreeSpace% GTR %DriveLimit% (
 Echo There is enough free space.
) else (
 Echo Not enough free space.
)

WMIC is the Windows Management Instrumentation component of Windows that comes with an assortment of commands you can use to pull PC information. This is how the “wmic” command in this script calls the “logicaldisk” space and places it into the FreeSpace variable. Now you can just replace the line “Echo Not enough free space” with a blat email command to send you an alert. computer science computer science computer science computer science
Finally, set this script up as a windows scheduled batch job that runs daily. computer science computer science
If you’ve never used blat before, we have an article that shows you how to set up blat. Unfamiliar with setting up scheduled jobs? We’ve got you covered with an article on how to set up Windows scheduled tasks.

data-full-width-responsive="true">
Prev1 of 4Next

Leave a Reply

Your email address will not be published. Required fields are marked *