locked
If else if condition in batch files RRS feed

  • Question

  • I have a batch file in which I am checking a string value returned from a WMI command.

    for /f "tokens=2 delims==" %%f in ('wmic /namespace:\some command /value ^| find "="') do set "myval=%%f"
    IF "%myval%"=="" ( echo Value Not found
    ) ELSE IF %myval:~0,1% NEQ # (
      echo Expected
    ) ELSE (
      echo Not expected
    )
    
    Rest of the file
    ....
    ...
    

    In my case the value returned by the WMI command is empty. so the first condition check is pass and it prints "Value not found". But after printing this, it checks the second condition to check for a"#" in the string returned of not empty. But this should not happen. So it gives unexpected results. Why so? Is the if else construct I have written correct? How can we ensure that only one condition is pass like in the normal if else according to the value returned?


    Monday, May 25, 2020 7:44 AM

Answers

  • Batch files are mostly obsolete in Windows.  You should not be using them for anything new.  We use PowerShell now.

    PowerShell is easier to use and learn than batch files.


    \_(ツ)_/

    • Marked as answer by Bill_Stewart Tuesday, June 30, 2020 7:26 PM
    Monday, May 25, 2020 8:05 AM

All replies

  • Batch files are mostly obsolete in Windows.  You should not be using them for anything new.  We use PowerShell now.

    PowerShell is easier to use and learn than batch files.


    \_(ツ)_/

    • Marked as answer by Bill_Stewart Tuesday, June 30, 2020 7:26 PM
    Monday, May 25, 2020 8:05 AM
  • I agree with jrv.

    Rather than trying to cobble together a solution that forces you to perform output string parsing of the WMIC command, use PowerShell which has access to WMI as objects.


    -- Bill Stewart [Bill_Stewart]

    Monday, May 25, 2020 11:56 PM
  • Thanks for the replies. Yes, I understand that batch files are legacy. But I need to work on this existing file. Thats it.
    Tuesday, May 26, 2020 2:24 PM
  •  But I need to work on this existing file. 
    There is nothing stopping you from adding a "Powershell c:\Scripts\SomeSubFunction.ps1" to your bat file to execute some specific portion of the application code that is easier to do in PS than .bat.  
    Wednesday, May 27, 2020 1:34 AM
  • Thanks for the replies. Yes, I understand that batch files are legacy. But I need to work on this existing file. Thats it.

    Your learning investment to rewrite your script using PowerShell will be well worth it.


    -- Bill Stewart [Bill_Stewart]

    Wednesday, May 27, 2020 10:03 PM
  • I figured out that batch files do not follow the usual programming style and is a bit different. It is better to use labels for each if condition. If using if-else then better to use a goto label inside in order to avoid unexpected case checking. Thanks
    Thursday, May 28, 2020 9:59 AM