Friday, August 10, 2012

Tokenize a string in batch

Earlier today I needed to pass a string to a function, and then split it into multiple tokens.
In my case I was looping through a large set of data in the function, and I wanted to compare it with multiple strings I was searching for.

Here's how I did it, with comments to explain =)
@echo off

call :TEST "String 1;String 2;String 3"
goto :EOF

:TEST
set str=%1                         REM Set the variable 'str' to the argument passed.
set str=%str:;=";"%                REM This is where the magic happens. Replaces all ';' characters in the string with '";"'
                                   REM This makes turns "String 1;String 2" into "String 1";"String 2"
for %%A in (%str%) do echo %%~A    REM And then we can loop through them and print them out one at a time.
goto :EOF

Thursday, August 9, 2012

Embed a VBScript inside a batch script

Recently I needed to resolve a shortcut, and well there is no way to do this in batch, you can in VBScript.

But I wanted to distribute a single batch file. Not a batch file and a VBScript file.
I also wanted to keep my script in batch - why? Because I like batch!

So here is what I came up with. It's pretty elegant compared to some of the other methods to do this I've seen.

 @echo off  
   
 echo Testing...  
 call :EXTRACTVBS START_RESOLVE_VBS Resolve.vbs  
 goto :EOF  
   
 :EXTRACT  
 set START=  
   
 for /f "tokens=*" %%A in ('type %~f0') do (  
     if defined START (  
         if "%%A" == "ENDVBS" goto :EOF  
         echo %%A>>%~2  
     ) else (  
         if "%%A" == "%~1" set START=1  
     )  
 )  
 goto :EOF  
   
 START_RESOLVE_VBS  
   
 Set objFSO = CreateObject("Scripting.FileSystemObject")  
 Set wshShell = WScript.CreateObject("WScript.Shell")  
 Set objShortcut = wshShell.CreateShortcut(Wscript.Arguments(0))  
 WScript.Echo objFSO.GetFileName(Wscript.Arguments(0)) + " : " + objShortcut.TargetPath  
   
 ENDVBS  
   

Everything after START_RESOLVE_VBS is not even seen by the batch script interpreter. So you can put anything there.
The :EXTRACT function takes 2 arguments, the first is the label that starts the VBScript, the second is an output path.

With this I can include multiple VBS files, or any text file for that matter, and call :EXTRACT to extract it.

Obtaining your IP address

There are many different methods to get your IP address in batch, but this is my new favorite.

 for /f "" %%A in ('hostname') do set HOSTNAME=%%A  
 for /f "tokens=2 delims=[]" %%A in ('ping %HOSTNAME% -4 -n 1 ^| find "Pinging"') do (  
     set IPADDR=%%A  
 )  

You can also change whether you want an IPv4 address or IPv6 address by changing the -4 argument to -6.

First post

First post...hurray!

I've recently taken an interest in writing batch scripts.
So, this blog is going to be a place for me to dump all the batch tricks I come up with that I can't find Googling around.