Quantcast
Channel: VMware Communities: Message List
Viewing all articles
Browse latest Browse all 225804

Re: Create a VM directory tree in vCenter (with folder exists check)

$
0
0

Hi,

your code looks quite fine, and I can reproduce that it runs fine if no folder exists. I get the same error when the folder exists.

 

in your buildFolderTree() function you have to return the folder object not only for the newly created folder, but also if the folder already exists (line 69 in the your posted code above). Otherwise the baseFolder variable will be undefined (line 28) triggering the error for the next run of buildFolderTree().

 

So something like

//////////////////////////////////////////////////////////////////////////////
// BUILD FUNCTION $buildFolderTree
function buildFolderTree(parentFolderObj, folderName) {  //Get a list of sublfolders  var children = parentFolderObj.childEntity;;  var allSubFolderNames = new Array();  var allSubFolderPropertiesList = new Array();  for (var i in children) {  if (children[i] instanceof VcFolder) {  var subfolderParent = children[i];  var subName = subfolderParent.name; //Get only the folder name  System.log("subfolder Name: " + subName);  var nameFolderProp = new Properties();  nameFolderProp.put("name", subName);  nameFolderProp.put("folderObject" , subfolderParent);  allSubFolderNames.push(subName); //Create an array of all subfolder names  allSubFolderPropertiesList.push(nameFolderProp); //Creat an array of all properties with subfolder objects  }  }  System.log("allSubFolders array: " + allSubFolderNames);  //Create folder if the folder does not already exists  var found = allSubFolderNames.indexOf(folderName); //Does $folderName exists in array.  False = -1  if (found != -1) {  System.log("Folder " + folderName + " already exists. Continue with next item");  return allSubFolderPropertiesList[found].get("folderObject");  }  if (found == -1) {  System.log("Building folder " + folderName);  var newFolder = parentFolderObj.createFolder(folderName);  System.log("Built directory: " + parentFolderObj.name + "/" + folderName);  return newFolder;  }  }
//////////////////////////////////////////////////////////////////////////////

does the job.

Feel free to improve it, I personally don't like the logic to identify the index of the allSubFolderPropertiesList - array by identifying the index in the other allSubFolderNames array. Creates an hard to find, but very strong dependency between the two arrays, and so leds to hard-maintainable code.

(That will be the daily vCO JavaScript Kata for tomorrow :-) )

 

Cheers,

Joerg


Viewing all articles
Browse latest Browse all 225804

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>