Thursday, February 14, 2008

Set And Setx

Everybody knows to use set to set environment variable values.  And I guess everybody should know setx.  The crucial differences between set and setx are:

  • set takes effect in local cmd context.  Meaning once you exit or close the cmd window, you lose the environment variable.
  • setx takes effect in future cmd context.  So you won't see the environment variable and its value in the current cmd.  You need to open a new cmd window to see it.

This really leads to one obvious conclusion: always use set and setx side by side if you want to set something globally but you want to see it in effect immediately.

A good example is if you want to set an environment variable containing your current IP address.  You would do something like this:

ipconfig | findstr IPv4 > %TEMP%\ipaddress.out

REM This will give you something like this

REM IPv4 Address. . . . . . . . . . . : 192.168.1.3

REM You then parse the output file, taking the second token after splitting at the ":"

for /F "delims=: tokens=2" %i in (%TEMP%\ipaddress.out) do (

    set IPADDR=%i

)

REM Then remove the spaces

set IPADDR=%IPADDR: =%

REM Then to persist this in the system environment, you call setx.

setx /M IPADDR %IPADDR%

Now of course setx is much more powerful than simply calling it the way I did in the above example.  Take a look at setx /? to see the complete options.  For example the above usage can also be done using setx alone.

ipconfig | findstr IPv4 > %TEMP%\ipaddress.out

REM Then you use setx to read its value from a file, keying in on a string,

REM and get the value relative to that string. In this case we key in on the ":"

REM and get the token after that.  And setx coordinates start at 0, not 1.

setx /M IPADDR /F %TEMP%\ipaddress.out /R 0,1 ":"

The reason I hardly ever use this is because most of the time I need the environment variable defined in the current context first, and then also persisting it for future cmd contexts.   The second example above only does it for future context.

Monday, January 21, 2008

Creating Compressed Directory

Often times I find myself in need of creating a directory with compressed attribute turned on, so I can put some text log files in with less space consumption.  While md or mkdir doesn't support doing this directly, you can create the directory and later apply the compression attribute, so that any subsequent files copied to that directory will be compressed.

md SomeDir

compact /C SomeDir

copy SomeText.log SomeDir

That does it.  Not the most useful thing in the world.  But hey, you never know when you will need it.

Friday, January 18, 2008

Out Parameter In Function Call

Let's say you write a function or procedure or sub program or whatever you want to call it in batch.  How do you pass back a value to the caller?  You can of course set an environment variable, but that's like setting a global variable.  And that's not very nice if you need to call the function multiple times and only use the value after all function calls are made.

Consider this example:

@echo off

call :GETVALUE

set INPUT1=%USERINPUT%

call :GETVALUE

set INPUT2=%USERINPUT%

echo %INPUT1% %INPUT2%

goto :EOF

 

:GETVALUE

set /P USERINPUT=Input?

goto :EOF

Like I said, it's doable, but not very nice.  I find it more soothing to the eyes if I can pass the variable name as an argument to the function.  And here's how you do it:

@echo off

call :GETVALUE INPUT1

call :GETVALUE INPUT2

echo %INPUT1% %INPUT2%

goto :EOF

 

:GETVALUE

set /P %1=Input?

goto :EOF

Nice and simple.  All you need to do is remember that you can use %1 and other %<number> on the left hand side of an assignment.  And it makes you think for a second that you are programming a real scripting language.

Thursday, January 17, 2008

Escape Characters

I know this is going to be a confusing year, because my first post of this year is on a topic I don't really understand.

For some time now I have been confused what the correct method to escape certain characters from being interpreted when I try to print them out.  Let's say I want to print this line:

< & >

I can't just say

echo < & >

Because I'll get an error that way (try it yourself if you don't believe me).  I have to escape those special characters.  To do that I can use the caret (^).

echo ^< ^& ^>

Nice and easy.  But then if I want to print this line:

%SYSTEMDRIVE%

The batch interpreter does something really baffling.  If I'm doing it from command line, I can escape it with a caret like other special characters.

echo ^%SYSTEMDRIVE^%

But it I do it from inside a batch file, that no longer works.  I have to escape the % not with a caret, but with another %.

echo %%SYSTEMDRIVE%

Confuse the hell out of me, I tell you.  So now I live by these rules:

  1. Always escape special characters using a caret in front of the special character.
  2. Except when you are in a batch file and need to escape a %, then use a %%.

I hope that helps some of you.  Oh wait, nobody reads this blog but me.  Oh, well.

Friday, October 19, 2007

Label at the End of Block

One thing I hate about batch file is, there is no real language definition you can refer to (or is there?).  So a lot of things I have to find out by myself the hard way.

Here's an example of this:

@echo off

for /L %%i in (1,1,10) do (

  if %%i GEQ 5 goto :NOPRINT

  echo %%i

  :NOPRINT

)

This gives an error saying that ") was unexpected at this time".  It is obvious what this means, and it is obvious how to fix it.  Just put a comment between the label and the closing bracket.

@echo off

for /L %%i in (1,1,10) do (

  if %%i GEQ 5 goto :NOPRINT

  echo %%i

  :NOPRINT

  REM can't have label immediately preceding closing bracket
)

I know this is not really anything useful, just a rant, that's all.

Evil Delayed Expansion

Wait, what's this?  How come something so useful as delayed expansion (see previous posts here and here to see how useful it is) be evil?  Well, it's not the feature itself that's evil, but rather the way you can end up spending a long time trying to figure out what's wrong if you make a simple, stupid mistake.

What mistake am I talking about?  Consider this:

@echo off

setlocal enabledelayedexpansion

set COUNT=0

for /L %%i in (1,1,10) do (

  set /A COUNT=%COUNT% + 1

  echo !COUNT!
)

Simple enough, you said.  And you must have spotted the bug (if you have not, try to run it and see what happens).  Now, of course if the loop body is much more complicated it would not be as easy.  You see, the problem is that what you are doing is completely legal.  Having %COUNT% in the loop body is fine as long as you don't expect it to be delay-expanded.  It's a feature, but when you make that silly mistake (or more likely, someone else in your team), then it's not going to be pleasant to hunt the problem down.

Wednesday, September 26, 2007

Using WaitFor

In Vista, there is a command called waitfor, which as the name suggests, waits for a signal.  It is also the command to send the signal to awaiting waitfor instances.  Since waitfor comes with a timeout option, it's a good substitute for sleep (which, until I found out about waitfor, really was the number one thing I could not understand why it's missing from standard Windows command).

waitfor /T 10 SomeSignal

The above command will simply times out after 10 seconds.

OK, I lied.  There is actually a real substitute for sleep in Windows.  It's the timeout command.

timeout /T 10

That command does the exact same thing as the waitfor example, but you can cut short the sleep for waitfor with some signal, whereas for timeout you cut it short by pressing a key.

But obviously the purpose of the waitfor command is to allow you to start some long running command, do some other shorter things, and  wait for the long running command to finish before continuing.

REM Let's pretend we need to setup something

start cmd /c "DoSetup.exe & waitfor /S %COMPUTERNAME% /SI ThisSignal"

DoSomethingElse.exe

waitfor /T 60 ThisSignal

The first waitfor sends the signal, the second waits for the signal.  Of course you want to make sure DoSomethingElse.exe actually finishes before DoSetup.exe for this to work.  Otherwise the second waitfor will just timeout.  And I'd advise against waiting forever in the second waitfor, since if your DoSetup.exe fails or crashes and exits early, you'll most likely end up waiting too late for a signal that's already sent.