Windows if and statement

if Statement

Conditionally execute a series of statements, based on the evaluation of the conditional expression.

[Attribute] if ( Conditional ) < Statement Block; >

Parameters

An optional parameter that controls how the statement is compiled.

Attribute Description
branch Evaluate only one side of the if statement depending on the given condition.

[!Note]
When you use Shader Model 2.x or Shader Model 3.0, each time you use dynamic branching you consume resources. So, if you use dynamic branching excessively when you target these profiles, you can receive compilation errors.

flatten Evaluate both sides of the if statement and choose between the two resulting values.

A conditional expression. The expression is evaluated, and if true, the statement block is executed.

Remarks

When the compiler uses the branch method for compiling an if statement it will generate code that will evaluate only one side of the if statement depending on the given condition. For example, in the if statement:

The if statement has an implicit else block, which is equivalent to x = x. Because we have told the compiler to use the branch method with the preceding branch attribute, the compiled code will evaluate x and execute only the side that should be executed; if x is zero, then it will execute the else side, and if it is non-zero it will execute the then side.

Conversely, if the flatten attribute is used, then the compiled code will evaluate both sides of the if statement and choose between the two resulting values using the original value of x. Here is an example of a usage of the flatten attribute:

There are certain cases where using the branch or flatten attributes may generate a compile error. The branch attribute may fail if either side of the if statement contains a gradient function, such as tex2D. The flatten attribute may fail if either side of the if statement contains a stream append statement or any other statement that has side-effects.

An if statement can also use an optional else block. If the if expression is true, the code in the statement block associated with the if statement is processed. Otherwise, the statement block associated with the optional else block is processed.

Windows if and statement

Performs conditional processing in batch programs.

Syntax

If command extensions are enabled, use the following syntax:

Parameters

Parameter Description
not Specifies that the command should be carried out only if the condition is false.
errorlevel Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
Specifies the command that should be carried out if the preceding condition is met.
== Specifies a true condition only if string1 and string2 are the same. These values can be literal strings or batch variables (for example, %1 ). You do not need to enclose literal strings in quotation marks.
exist Specifies a true condition if the specified file name exists.
Specifies a three-letter comparison operator, including:
  • EQU — Equal to
  • NEQ — Not equal to
  • LSS — Less than
  • LEQ — Less than or equal to
  • GTR — Greater than
  • GEQ — Greater than or equal to
/i Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2 are comprised of numeric digits only, the strings are converted to numbers and a numeric comparison is performed.
cmdextversion Specifies a true condition only if the internal version number associated with the command extensions feature of Cmd.exe is equal to or greater than the number specified. The first version is 1. It increases by increments of one when significant enhancements are added to the command extensions. The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined Specifies a true condition if variable is defined.
Specifies a command-line command and any parameters to be passed to the command in an else clause.
/? Displays help at the command prompt.

Remarks

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause.

When a program stops, it returns an exit code. To use exit codes as conditions, use the errorlevel parameter.

If you use defined, the following three variables are added to the environment: %errorlevel%, %cmdcmdline%, and %cmdextversion%.

%errorlevel%: Expands into a string representation of the current value of the ERRORLEVEL environment variable. This variable assumes that there isn’t already an existing environment variable with the name ERRORLEVEL. If there is, you’ll get that ERRORLEVEL value instead.

%cmdcmdline%: Expands into the original command line that was passed to Cmd.exe prior to any processing by Cmd.exe. This assumes that there isn’t already an existing environment variable with the name CMDCMDLINE. If there is, you’ll get that CMDCMDLINE value instead.

%cmdextversion%: Expands into the string representation of the current value of cmdextversion. This assumes that there isn’t already an existing environment variable with the name CMDEXTVERSION. If there is, you’ll get that CMDEXTVERSION value instead.

You must use the else clause on the same line as the command after the if.

Examples

To display the message Cannot find data file if the file Product.dat cannot be found, type:

To format a disk in drive A and display an error message if an error occurs during the formatting process, type the following lines in a batch file:

To delete the file Product.dat from the current directory or display a message if Product.dat is not found, type the following lines in a batch file:

These lines can be combined into a single line as follows:

To echo the value of the ERRORLEVEL environment variable after running a batch file, type the following lines in the batch file:

To go to the okay label if the value of the ERRORLEVEL environment variable is less than or equal to 1, type:

Windows batch if statement with user input

A .bat should compare user input with a value. It doesn’t go inside the IF «%choice%»==»1» when I test it with an input of 1 or 2.

Here is the batch file :

The command output:

Why is it not going inside the IF «%choice%»==»1» condition?

2 Answers 2

Here is a working batch code:

Delayed expansion is enabled at top of the batch file with command setlocal EnableExtensions EnableDelayedExpansion . The command SETLOCAL does not only enable delayed expansion, it saves entire command process environment on stack as explained in detail in my answer on change directory command cd ..not working in batch file after npm install. The command process environment is restored from stack on execution of command ENDLOCAL which would be also done by Windows command processor on exiting batch file processing when not explicitly executing endlocal .

All environment variables set or modified in a command block starting with ( and ending with matching ) and also referenced within same command block must be referenced using delayed expansion.

When Windows command processor reaches the fourth line, the entire command block up to last but one line is parsed and preprocessed before the IF condition is evaluated at all. All environment variables referenced with percent signs are expanded on this preprocessing step in entire block from the line 4 to the line 36.

That means all occurrences of %ecb% and %bdf% are replaced by the current values of the environment variables ecb and bdf before the IF condition on line 4 is evaluated at all like %$ecbId% in IF condition itself.

Just the environment variable UserChoice is not expanded on parsing/preprocessing the entire block as this environment variable is referenced using delayed expansion.

Therefore it is possible to assign a default value like abort to the environment variable UserChoice kept in case of batch user hits just RETURN or ENTER without entering anything at all.

The string entered by the user is never expanded on a parsing/preprocessing stage because of using delayed expansion for environment variable UserChoice . The current string value of UserChoice is always interpreted on evaluating each IF condition.

This behavior of Windows command processor can be watched easily by

  1. removing @echo off from first line of batch file,
  2. opening a command prompt window,
  3. running in command prompt window the batch file by entering the name of the batch file with full path if current directory is not the directory of the batch file.

The Windows command processor outputs now always the line or command block after parsing before it is really executed. So it can be seen that on reaching first IF condition, the entire command block is already preprocessed with replacing all occurrences of %. % with the appropriate strings from the environment variables respectively nothing if the reference environment variable is not defined yet. And it can be seen that the values of %ecb% and %bdf% are never modified again while next command lines within the entire command block are executed by Windows command interpreter.

More compact would be:

Another solution is using the command choice which is available by default since Windows Vista. It has the advantage that the user just needs to press one of three keys. Delayed environment variable expansion is not needed in this case as choice exits with a value depending on the pressed key which is assigned to the environment variable errorlevel which can be evaluated without delayed expansion even within a command block.

The user has to press 1 resulting in choice exiting with value 1 because of character 1 is specified as first character after option /C , or key 2 to let choice exit with value 2 , or key A (case-insensitive) resulting in an exit of choice with value 3 as character A was specified as third character in next argument string after option /C . There can be additionally pressed Ctrl+C to exit batch file processing after an additional confirmation. All other key presses are ignored by choice and result in a bell noise output for notification of the user about having pressed wrong key.

It is best nowadays to use the command choice for such user prompts with just file name or with full qualified file name for maximum execution safety.

IF… OR IF… in a windows batch file

Is there a way to write an IF OR IF conditional statement in a windows batch-file?

14 Answers 14

The zmbq solution is good, but cannot be used in all situations, such as inside a block of code like a FOR DO(. ) loop.

An alternative is to use an indicator variable. Initialize it to be undefined, and then define it only if any one of the OR conditions is true. Then use IF DEFINED as a final test — no need to use delayed expansion.

You could add the ELSE IF logic that arasmussen uses on the grounds that it might perform a wee bit faster if the 1st condition is true, but I never bother.

Addendum — This is a duplicate question with nearly identical answers to Using an OR in an IF statement WinXP Batch Script

Final addendum — I almost forgot my favorite technique to test if a variable is any one of a list of case insensitive values. Initialize a test variable containing a delimitted list of acceptable values, and then use search and replace to test if your variable is within the list. This is very fast and uses minimal code for an arbitrarily long list. It does require delayed expansion (or else the CALL %%VAR%% trick). Also the test is CASE INSENSITIVE.

The above can fail if VAR contains = , so the test is not fool-proof.

If doing the test within a block where delayed expansion is needed to access current value of VAR then

FOR options like «delims=» might be needed depending on expected values within VAR

The above strategy can be made reliable even with = in VAR by adding a bit more code.

But now we have lost the ability of providing an ELSE clause unless we add an indicator variable. The code has begun to look a bit «ugly», but I think it is the best performing reliable method for testing if VAR is any one of an arbitrary number of case-insensitive options.

Finally there is a simpler version that I think is slightly slower because it must perform one IF for each value. Aacini provided this solution in a comment to the accepted answer in the before mentioned link

The list of values cannot include the * or ? characters, and the values and %VAR% should not contain quotes. Quotes lead to problems if the %VAR% also contains spaces or special characters like ^ , & etc. One other limitation with this solution is it does not provide the option for an ELSE clause unless you add an indicator variable. Advantages are it can be case sensitive or insensitive depending on presence or absence of IF /I option.

PowerShell Basics: If -And & If -Or Statements

Introduction to The Windows PowerShell If -And Statement

One of the best statements for filtering data is the ‘If’ clause. For scripts that require precise flow control you could incorporate PowerShell’s -And, the benefit is that your test could now include multiple conditions.

Topics for PowerShell’s If -And Statement

Introduction to the PowerShell ‘If’ -And Statement

The key point is that you only need one ‘If’.

Summary: The PowerShell ‘If’ conditionally executes a statements, depending on the truth of the test expression.

Example 1: Basic ‘If’ Test

If you are new to PowerShell’s implementation of If statement then it’s worth starting with a plain ‘If’ flow control before adding -And.

Learning Points

Note 1: Trace the construction, and separate into two components: if (test) and .

Note 2: Avoid over-think; there is no ‘Then’ in a PowerShell ‘If’ statement. My advice is that instead of worrying about ‘Then’, pay close attention to the two types of bracket. Furthermore, there is no endif in PowerShell as there is in VBScript.

Note 3: To double check your understanding, try amending, $Calendar.Month -eq ‘5’ to a different number, such as: ’12’. Once you have done that, change: Else .

Example 2: PowerShell If -And Script

The purpose of this script is merely to test different dates and compare them with today’s date, which is held by the variable $Calendar.

Multiple -And Conditions

Once your flow control works with one -And, it’s straightforward (if a little clumsy) to append more -And conditions. Avoid ‘overthink’, you only need one set of (parenthesis brackets).

Here is an additional example with a few more statements containing -And

Note 4: Pay close attention to the (first parenthesis). In particular find the two tests: “.day -eq ’25’ “, also “.Month -eq ’12’ “. My first point is they are separated by -And. My second point is there is only one set of (condition brackets).

Note 5: I included a few ElseIfs and a final Else statement to give the script a little more context, and to give ideas for modifying your scripts.

Guy Recommends: Free WMI Monitor for PowerShell (FREE TOOL)

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems. Fortunately, SolarWinds have created a Free WMI Monitor for PowerShell so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guesswork out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Example 3: PowerShell -And Statement

Here is an example using logic to check whether you have a standard installation of your Microsoft Windows operating system.

Note 5: There are no commas in this construction, in particular, there is no special syntax before the -And.

Example 4: PowerShell -Or Example

The reason for including this example is that -Or follows the same pattern as PowerShell’s -And.

While this script is designed to test the tiny ‘-Or’ syntax, it has lots of extraneous code which changes the startupType to manual. The sole purpose of this convoluted layout is so that you can check the logic and thus understand how -Or works in PowerShell.

Production script:
In real life you may want to strip the code down, and append a command to actually start the spooler service.

Note 6: It’s always difficult to get the balance between example scripts that illustrate a point and those that do useful work.

Note 7: Once If statements get complicated it’s time to investigate PowerShell’s Switch parameter.

Guy Recommends: Network Performance Monitor (FREE TRIAL)

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network. This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems. Its also has the ability to monitor the health of individual VMware virtual machines. If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

Researching PowerShell’s If -And

For more information refer to the built-in About_If file

Summary of PowerShell’s If -And Construction

When it comes to filtering output, one of the oldest and best statements is the ‘If’ clause. As usual, the secret of understanding the syntax is to pay close attention to the style bracket. If (parenthesis for the test) and . Once you have mastered the basic ‘If’ statement, then extend your capabilities by introducing ‘-And’.

If you like this page then please share it with your friends

See more Windows PowerShell flow control examples

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

Читайте также:  Application blocked by java security mac os
Оцените статью