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.

No comments:

Post a Comment