November 11, 2014 · wsh windows script host javascript

Windows Script Host(WSH) Javascript Create directory from path

The Microsoft Windows Script Host (WSH) is an automation technology for Microsoft Windows operating systems that provides scripting capabilities comparable to batch files, but with a greater range of supported features. It was originally called Windows Scripting Host, but was renamed for the second release. WSH (VBS) is a very useful tool that allows you to run JScript, VBScript, and XML scripts natively within the OS.

You can read more about Windows Script Host(WSH) on Microsoft official site.

Back to the subject. How to create directories and subdirectories from String path using JScript and Windows Script Host? Process is quite simple and still there is no support for this simple functionality out of box in WSH.

First we must tokenize input and extract each directory name as separate String. We can achieve this using Regular Expressions. I have following pattern:

 var pattern = /(.*?)\\/gm;

The final step is to create folders, starting with the root folder to the last one.

Additionaly you can add check wheter Directory exists before trying to create one. Check if Directory exists in Windows Script Host can be achieved calling method object.FolderExists(folder).

More specific information about this method can be found on msdn.

 // author: Stankovic Vlada (

 var debug = true;
 var pattern = /(.*?)\\/gm;
 var path = "c:\\test\\test1\\test2\\test3\\";
 var fileSystemOut = new ActiveXObject("Scripting.FileSystemObject");
 createDirectoryFromPath(fileSystemOut, path, pattern);

 // Java Script function that creates folder tree from input String
 // @param fileSystemOut 
 // File System Object (FSO) Provides access to a computer's file system.
 // @param path - Full path that represents directory tree 
 // (for example var path = "c:\\test\\test1\\test2\\test3\\")
 // @param pattern - Regex pattern that tokenize path
 //  String to individual directories
 function createDirectoryFromPath(fileSystemOut, path, pattern) {
     var tmpFileLoc = "";
     while (result = pattern.exec(path)) {
         tmpFileLoc = tmpFileLoc.concat(result[0]);
         if(debug == true)
             WScript.echo("Creating dir - >" + tmpFileLoc);
         try {
         } catch(e) {
             if(debug == true)
                 WScript.echo("***ERROR while creating Folder: "
                                                        + e.description);

File System Object (FSO)

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus