1

I need to have a IF statement in a batch file that takes different action based on the FileName. The action doesn't matter as I have that part handled. What I can't figure out is how to get my IF statement to work. I tried to substring the FileName but can't get it to work. In short, I want to do one thing if the FileName has "Orders" and another if it has "Accessories" in the name.

IF "%1:~0,18%" == MyFileName1_Orders (
    sqlcmd MyCommand )

IF "%1:~0,23%" == MyFileName1_Accessories (     
    sqlcmd MyCommand )

Thanks in advance

Thanks for the reply Magoo. I did as you showed but unfortunately it still doesn't work. In this batch file the only thing I have are these 3 lines now, beginning with: set "name=%1". Still no luck.

I also tried to see if the file "contains" the words I'm trying to substring but I can't get it to fire off my sqlcmd line. I followed this example. I can get it to echo out the correct stuff so I know it's working, but it doesn't seem to fire off the (sqlcmd...) part. If the sqlcmd part was the only thing in the batch file it works flawlessly every time. Batch file: Find if substring is in string (not in a file)

Paul I also tried your suggestion and I have the same results; it doesn't fire off my sqlcmd. And like I said, this sqlcmd has been working for years just fine, and continues to work if it's the only thing in the bat file. As soon as I add the IF, it stops working.

Andre
  • 11
  • 3
  • 2
    Both sides of the condition would only match if they were both enclosed with double quotes. Additionally variables should be alphabet characters. – Compo Jun 10 '17 at 01:08

3 Answers3

0

Substringing is not supported for metavariables - you need to transfer the value to an ordinary environment variable.

set "name=%1"
IF "%name:~0,18%" == "MyFileName1_Orders" ( sqlcmd MyCommand )

should work, assuming that these isolated lines of code are contained in a subroutine where the name is being supplied as the first parameter.

And if one parameter of an if is quoted, then both must be

Magoo
  • 77,302
  • 8
  • 62
  • 84
0

Try something like:

set fn=%~1
if not "%fn:orders=%" == "%fn%" ( sqlcmd MyCommand )
if not "%fn:accessories=%" == "%fn%" ( sqlcmd MyCommand )
Paul Houle
  • 735
  • 9
  • 17
0

Nevermind on this question - I used Powershell instead and it works like a champ. Thanks for all the replies.

Andre
  • 11
  • 3