Counting DNS Zones in Windows Server 2008/2012 with Microsoft Jscript

Once I had to automate the process of getting info about the DNS zones sitting on some abstract Windows server. Again it cuts at my brain that I’m writing a note about Windows, when this blog was originally meant for Linux stuff.

So the task is clear. The choice of tool fell on Jscript, since the main module’s body is written in it - writing the second part in PowerShell wouldn’t be proper. Decided: I'll count files with the *.dns extension in the C:\Windows\System32\dns folder, strip their extension, and count them.

Declare the initial variables, initialize the shell:

var env = new ActiveXObject("WScript.Shell").Environment("Process");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = env("WINDIR") + '\\System32\\dns';

You absolutely need to make sure the folder exists and there are zones in it, otherwise the script will throw an error. Add a condition checking that the fso (file system object) exists:
if (fso.FolderExists(path) == true){

Next read the folder contents, strip the path, and write the resulting data into the dnsfiles array

var folder = fso.GetFolder(path);
var myEnum = new Enumerator(myFolder.Files);

myEnum.moveFirst();
while(!myEnum.atEnd()){
	var re =new RegExp('[^\\\\]*dns$', "gi");
	var file = re.exec(myEnum.item());
	if ((file != null) && (file != "cache.dns") && (file != "CACHE.DNS")){
		var dnsrecord = new RegExp("\.dns", "i");
		dnsrecord.exec(file);
	}
	myEnum.moveNext();
}

You can use the same principle to list the contents of other directories.

Full script:
var env = new ActiveXObject("WScript.Shell").Environment("Process");
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	var path = env("WINDIR") + '\\System32\\dns';

	if (fso.FolderExists(path) == true){

  	var myFolder = fso.GetFolder(path);
  	var myEnum = new Enumerator(myFolder.Files);
  	var nn = 1;

  	WScript.Echo("");
  	WScript.Echo("System DNS zones: ");

  	myEnum.moveFirst();

  	while(!myEnum.atEnd()){
  		var re =new RegExp('[^\\\\]*dns$', "gi");
  		var file = re.exec(myEnum.item());
  		if ((file != null) && (file != "cache.dns") && (file != "CACHE.DNS")){
 				var dnsrecord = new RegExp("\.dns", "i");
 				dnsrecord.exec(file)
 				WScript.Echo(nn+': '+RegExp.leftContext);
 				num += nn;
  		}
  		myEnum.moveNext();
  	}
  }

Links to MSDN: