vRealize Orchestrator script for RV tool







-----------------------------Code of Script to Pull Information----------------------------


var i,j, vmName;
var contentMessage,logtxtDisk,logtxtNIC,logtxtNetwork;
content = "VM Name,HostName,Cluster,PowerState,RAM,CPU,Core,IP Address,OS \n";
vdiskcontent = "VM Name,vDisk,Path,Size,DataStore \n";
vNetwork = "VM Name,Type,Port group \n";
logtxtHNetwork = "Hostname,vNic,Driver,Address,DevID,PortID,CDP Info \n";
contentMessage = "Hi Team, <br> <br> PFA VMs report. <br> <br> Thanks<br> Manoj";
for ( i in clustername )
{
actionResult = System.getModule("com.vmware.library.vc.cluster").getAllVMsOfCluster(clustername[i]);
                for ( j in actionResult)
                {
                                vmName = actionResult[j].name;
                                var guest = actionResult[j].runtime;
                                var hostname = guest.host.name;
                                var cluster = (actionResult[j].runtime.host).parent;
                                logtext =  vmName + "," + hostname + "," + cluster.name + "," + actionResult[j].runtime.powerState.value + "," + actionResult[j].config.hardware.memoryMB + "," +  actionResult[j].config.hardware.numCPU + "," + actionResult[j].config.hardware.numCoresPerSocket + "," + actionResult[j].guest.ipAddress + "," + actionResult[j].guest.guestFullName + "\n";
                                content = content +  logtext ;
                                //Get Datastores
                                var datastoresProp = new Properties();
                                var diskSizes = new Array();
                                var devices = actionResult[j].config.hardware.device;
                                var l = 0;
                                for (var k in devices)
                                {
                                                if (devices[k] instanceof VcVirtualDisk)
                                                {
                                                                diskSizes[l++] = devices[k].capacityInKB / 1048576;
                                                                var vmdkSize = devices[k].capacityInKB / 1048576;
                                                                var datastore = devices[k].backing.datastore;
                                                                var vmdkName = devices[k].deviceInfo.label;
                                                                var vmdkFName = devices[k].backing.fileName;
                                                                logtxtDisk = vmName + "," + vmdkName + "," + "," + vmdkFName + "," + vmdkSize + "," + datastore.name + "\n";
                                                                vdiskcontent = vdiskcontent + logtxtDisk;                                           
                                                }
                                                if ( devices[k] instanceof VcVirtualVmxnet3)
                                                {
                                                                logtxtNIC = vmName + ",vmxnet3, " + devices[k].backing.deviceName + "\n";
                                                                vNetwork = vNetwork + logtxtNIC;
                                                }
                                                if ( devices[k] instanceof VcVirtualVmxnet2)
                                                {
                                                                logtxtNIC = vmName + ",vmxnet2, " + devices[k].backing.deviceName+ "\n";
                                                                vNetwork = vNetwork + logtxtNIC;
                                                }
                                                if ( devices[k] instanceof VcVirtualPCNet32)
                                                {
                                                                logtxtNIC = vmName + ",PCNet32, " + devices[k].backing.deviceName+ "\n";
                                                                vNetwork = vNetwork + logtxtNIC;
                                                }
                                                if ( devices[k] instanceof VcVirtualE1000)
                                                {
                                                                logtxtNIC = vmName + ",E1000, " + devices[k].backing.deviceName+ "\n";
                                                                vNetwork = vNetwork + logtxtNIC;
                                                }
                                }
                }
}
/*Start - Code to get DataStore and NAA id */
var vdatastoretxt, hostcount, naaid, hname_ds;
var datastore, datastores;
vdatastoretxt = "DataStore,HostCount,HostName,VM Count,URL,Type,MHA,UUID,NAAID \n";
datastores = System.getModule("com.vmware.library.vc.datastore").getAllDatastores();
for each ( datastore in datastores)
{
                try{
                System.log(datastore.name);
                var hosts_ds = datastore.host;
                hname_ds = " ";
                naaid = " ";
                for each (var host_ds in hosts_ds)
                {
                                hname_ds  =  host_ds.key.name + hname_ds;
                }
                if (hosts_ds.length != 0)
                {
                hostname = hosts_ds[0].key;
                for each (var mountedVolume in hostname.configManager.storageSystem.fileSystemVolumeInfo.mountInfo)
                {
                                for each( var volumeExtent in mountedVolume.volume.extent)
                                {
                                                if(mountedVolume.volume.name.match(datastore.name))
                                                {
                                                                var volumeMountinfo = mountedVolume.mountinfo;
                                                                System.log(volumeExtent.diskName);
                                                                naaid = volumeExtent.diskName + naaid;
                                                }             
                                }
                }
                }
                vdatastoretxt  = vdatastoretxt + datastore.name + "," + hosts_ds.length + "," + hname_ds +  "," + datastore.vm.length + "," + datastore.info.url + "," + datastore.summary.type + "," + datastore.summary.multipleHostAccess + "," + datastore.info.vmfs.uuid + "," + naaid + "\n";
                }
                catch (ex)
                {
                  throw "Error"
                }
}
/* End - Datastore & NAA id */

/* Start - Code to Pull Portgroup Information */
var pg_hosts,pg_hostname;
var portgroup,portgroups,vmNics,porttxt;
var promiscuous,ftransmit, macchange;
porttxt = "HostName,Portgroup,VLAN ID,vSwitch,Promiscuous,ForgedTransmits,MacChange,Policy \n";
for ( i in clustername )
{
pg_hosts = System.getModule("com.vmware.library.vc.cluster").getAllHostSystemsOfCluster(clustername[i]);
for each(pg_host in pg_hosts)
{
                pg_hostname = pg_host.name;
                System.log(pg_hostname);
                portgroups = pg_host.configManager.networkSystem.networkInfo.portgroup;
                for each (portgroup in portgroups)
                {
                                if(portgroup.spec.policy.security.allowPromiscuous == "TRUE")
                                {
                                                promiscuous = "True";
                                }
                                else
                                {
                                                promiscuous = "False";
                                }
                                if((portgroup.spec.policy.security.forgedTransmits) = "TRUE")
                                {
                                                ftransmit = "True";
                                }
                                else
                                {
                                                ftransmit = "False";
                                }
                                if((portgroup.spec.policy.security.macChanges) = "TRUE")
                                {
                                                macchng = "True";
                                }
                                else
                                {
                                                macchng = "False";
                                }
                                porttxt = porttxt + pg_hostname + "," + portgroup.spec.name + "," + portgroup.spec.vlanId + "," + portgroup.spec.vswitchName + "," + promiscuous + "," + ftransmit + "," + macchng + "," + portgroup.spec.policy.nicTeaming.policy + "\n";
                System.log(porttxt);
                }
}
}
/* End - Code to Pull Portgroup Information */

/* Start - Code to pull Network information of Host */
var txtNetwork = ";";
var nw_hosts,nw_host,pNic,pnicInfos,pnicInfo,nic,network,networks;
for ( i in clustername )
{
                nw_hosts = System.getModule("com.vmware.library.vc.cluster").getAllHostSystemsOfCluster(clustername[i]);
                for each(nw_host in nw_hosts)
                {
                                pNic = nw_host.configManager.networkSystem.networkInfo.pnic;
                                pnicInfos = nw_host.configManager.networkSystem.queryNetworkHint();
                                for each (pnicInfo in pnicInfos)
                                {
                                                if(pnicInfo.connectedSwitchPort)
                                                {
                                                                for each (nic in pNic)
                                                                {
                                                                                if( nic.device == pnicInfo.device)
                                                                                {
                                                                                                networks = pnicInfo.subnet;
                                                                                                for each ( network in networks)
                                                                                                {
                                                                                                                txtNetwork = network.ipSubnet + "(VLAN:" +  network.vlanId + ")" + txtNetwork;
                                                                                                }
                                                                                                logtxtHNetwork = logtxtHNetwork + nw_host.name + "," + pnicInfo.device +  "," + nic.driver + "," + pnicInfo.connectedSwitchPort.address +  "," + pnicInfo.connectedSwitchPort.devId + "," + pnicInfo.connectedSwitchPort.portId +  "," + txtNetwork + "\n";
                                                                                }
                                                                }
                                                }
                                                else
                                                {
                                                                logtxtHNetwork = logtxtHNetwork + nw_host.name + "," + pnicInfo.device +  ",No Information,No Information,No Information,No Information,No Information \n";
                                                }
                                }
                }
}
/* End - Code to pull Network information of Host */

var message = new EmailMessage();
// Override default settings if and only if input parameter is set
if ( smtpHost != null && smtpHost.length > 0 ){
    message.smtpHost = smtpHost;
}
if ( smtpPort != null && smtpPort > 0 ){
    message.smtpPort = smtpPort;
}
if ( fromName != null && fromName.length > 0){
    message.fromName = fromName;
}
if ( fromAddress != null && fromAddress.length > 0){
    message.fromAddress = fromAddress;
}
message.toAddress = toAddress;
message.subject = subject;
message.ccAddress = ccAddress;
message.addMimePart(contentMessage,"text/html; charset=UTF-8");
//Create Attachment
var fileAttachment = new MimeAttachment();
fileAttachment.name = "vmsReport.csv";
fileAttachment.content = content;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");
fileAttachment.name = "vDiskReport.csv";
fileAttachment.content = vdiskcontent;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");
fileAttachment.name = "vNetwork.csv";
fileAttachment.content = vNetwork;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");
fileAttachment.name = "vDatastore.csv";
fileAttachment.content = vdatastoretxt;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");
fileAttachment.name = "vPortgroup.csv";
fileAttachment.content = porttxt;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");
fileAttachment.name = "vHostNetwork.csv";
fileAttachment.content = logtxtHNetwork;
message.addMimePart(fileAttachment,"application/zip");// charset=UTF-8");

System.log( "sending mail to host: " + message.bccAddress + ":" + message.smtpPort + " with user:" + message.username + ", from:" + message.fromAddress + ", to:" + message.toAddress );
message.sendMessage();

-----------------------------------------End of Script Code----------------------------------



Limit of Scripts:
1. Scsi bus sharing
2. RDM Info.

You are welcome to modify the script.






SnapShot report of Linux/Windows server using vRealize Orchestrator

This is my first vRealize Orchestrator script to pull the information of snapshots of virtual machine x hours old.










Once you are done with attibutes and input/output parameters, time to write script.

----------------------------------Code to pull snapshot report-------------------------------
ar now = new Date();

var now_minus_hours = new Date();
now_minus_hours.setHours(now.getHours() - max_hours);
var i, logtext, contentMessage ;
System.log("Listing snapshots, older than: "+ now_minus_hours);
var vms = System.getModule("com.vmware.library.vc.vm.os").getAllLinuxVMs() ;
content = "VM Name,Power State,Snapshot Name \n";
var outStr = "";
contentMessage = "Hi Team, <br> <br> PFA snapshot status of Linux servers. <br> <br> Thanks<br> Manoj";
for (i in vms)
{
                var vm = vms[i];
                if(vm.snapshot)
                {
                                var allSnaps = new Array();
                                var allParents;
                                var snapshot = vm.snapshot;
                                var Power = vm.runtime.powerState.value;
                                var rootSnapshotList = snapshot.rootSnapshotList;
                                for each (var rsnap in rootSnapshotList)
                                {
                                getSnapshotsOfVM(rsnap);
                                }
                for each (var snap in allSnaps)
                                {
                                if(snap.createTime < now_minus_hours)
                                                {
                                                                //System.log("VM Name: " + snap.vm.name + " Snapshot Name: " + snap.name + " Snapshot creation time: " + snap.createTime.toLocaleString());
                                                                logtext = snap.vm.name + "," + Power + "," + snap.name + "\n";
                                                                content = content +  logtext ;
                                                }
                                }

     }
}

function getSnapshotsOfVM(snapshotTree)
{
    allSnaps.push(snapshotTree);
    var childTrees = snapshotTree.childSnapshotList;
    if(childTrees != null) {
        for(var index in childTrees) {
            if(childTrees[index] != null) {
                getSnapshotsOfVM(childTrees[index]);
            }
        }
    }
}

var message = new EmailMessage();
// Override default settings if and only if input parameter is set
if ( smtpHost != null && smtpHost.length > 0 ){
    message.smtpHost = smtpHost;
}
if ( smtpPort != null && smtpPort > 0 ){
    message.smtpPort = smtpPort;
}
if ( fromName != null && fromName.length > 0){
    message.fromName = fromName;
}
if ( fromAddress != null && fromAddress.length > 0){
    message.fromAddress = fromAddress;
}
message.toAddress = toAddress;
message.subject = subject;
message.ccAddress = ccAddress;
message.addMimePart(contentMessage,"text/html; charset=UTF-8");
//Create Attachment
var fileAttachment = new MimeAttachment();
fileAttachment.name = "SnapShot_Linux.csv";
fileAttachment.content = content;
message.addMimePart(fileAttachment,"application/json; charset=UTF-8");
System.log( "sending mail to host: " + message.bccAddress + ":" + message.smtpPort + " with user:" + message.username + ", from:" + message.fromAddress + ", to:" + message.toAddress );
message.sendMessage();

-------------------------------End Code to pull snapshot report-----------------------------

Please replace below line if you want to pull snapshot report of Windows servers.

var vms = System.getModule("com.vmware.library.vc.vm.os").getAllWindowsVMs() ;

Blow is written since long time, you are welcome to comment here.


How to Run Performance counter when Available RAM is Below threshold

Here, you will learn how to execute Performance counters once configured Alert reached below/above threshold value. I am configuring alert for RAM and trying to capture the performance counter report of running processes when memory will go below threshold value. Performance counter to monitor the performance will be triggered off  automatically once value reached below threshold. To do so, we will first create Alert in Perfmon to monitor the threshold value of RAM and then create counters for running process.

With this scenario, we will be able to find the list of processes running when RAM goes below threshold value. You can configure performance counters as per your requirement.

Lets go!!! Steps are given below.

1. Open Perfmon.
2. Create Alert for threshold value of RAM.



Here, we will select second option to create Alert for Memory.



Here, Add counter which you want to monitor, I am using Available memory(MB) to monitor Physical memory.


Configure the threshold value(Limit) for Available memory, I am using below 250 MB.



3. Create Performance counter for Process




Configure required counters. I am using Process to monitor, make sure select only "<All instances>" (as shown in below fig.) instead of selecting all process as I have to capture all the running processes when memory went to below threshold.




4. Now both alter and counters have been configured. Now, we have to configure Alert so that required performance can be triggered off once value reached to threshold value.

5. Go to Property of Alert and click Alert Action tab then select data collector name as created above.

6. Once all done, start only Alert. It will monitor the memory threshold value and once reached; it will triggered off  performance counters to monitor the running process.

I have explained logic which can be used as per requirement. I have done this to capture the running processes performance counters when threshold value of memory reaches below to 250 MB.

Same can be done to CPU as well..........

Script to list larger size folder with owner detail

Script is modified by me as per my requirement. It is parameter based script. Example is given below.

cscript folder.vbs "C:\Program Files" 1GB

Above execution will search folder larger than 1 GB in Program Files along with owner.

--------------------------------
Path = WScript.Arguments.Item(0)
Data1 = WScript.Arguments.Item(1)
Format = UCase(Right(Data1,2))
Data = Left(Data1,Len(Data1)-2)
Set objWMIService = GetObject("winmgmts:")
If Format <> "GB"And Format <> "MB"Then
MsgBox"Data Format Error!!! Please correct"
WScript.Quit
EndIf
Dim fso
Dim ObjOutFile
'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Create an output file
Set ObjOutFile = fso.CreateTextFile("c:\Output.csv")

'Writing CSV headers
If Format = "GB"Then
ObjOutFile.WriteLine("Type,Folder Name,Path,Size(GB), Owner")
Else
ObjOutFile.WriteLine("Type,Folder Name,Path,Size(MB), Owner")
EndIf

'Call the GetFile function to get all files
GetFiles(Path)

'Close the output file ObjOutFile.Close
WScript.Echo("Completed")

Function GetFiles(FolderName)
OnErrorResumeNext
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Set ObjFolder = fso.GetFolder(FolderName)
'Getting all subfolders
Set ObjSubFolders = ObjFolder.SubFolders

ForEach ObjFolderIn ObjSubFolders
'Writing SubFolder Name and Path
If Format = "GB"Then
    Size=Round(((ObjFolder.Size)/(1024*1024*1024)),2)
EndIf
If Format = "MB"Then
    Size=Round(((ObjFolder.Size)/(1024*1024)),2)
EndIf
If Size > Int(data) Then
strFolderName = ObjFolder
WScript.Echo strFolderName
Set objFileSecuritySettings = objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFolderName & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
WScript.Echo objSD.Owner.Name
If intRetVal = 0Then
   ObjOutFile.WriteLine(ObjFolder.Type & "," & ObjFolder.Name & "," & ObjFolder.Path & "," & Size & "," & objSD.Owner.Domain & "\" & objSD.Owner.Name )
Else
   ObjOutFile.WriteLine(ObjFolder.Type & "," & ObjFolder.Name & "," & ObjFolder.Path & "," & Size & ", Unable to find")
EndIf
EndIf
'Getting all Files from subfolder
GetFiles(ObjFolder.Path)
Next
EndFunction

Script to list larger files with owner detail

Script is modified by me as per my requirement. It is parameter based script. Example is given below.

cscript file.vbs "C:\Program Files" 1GB


Above execution will search file larger than 1 GB in Program files along with owner.


--------------------------------

Path = WScript.Arguments.Item(0)
Data1 = WScript.Arguments.Item(1)
Format = UCase(Right(Data1,2))
Data = Left(Data1,Len(Data1)-2)
Set objWMIService = GetObject("winmgmts:")
If Format <> "GB"And Format <> "MB"Then
MsgBox"Data Format Error!!! Please correct"
WScript.Quit
EndIf
Dim fso
Dim ObjOutFile
'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Create an output file
Set ObjOutFile = fso.CreateTextFile("c:\Output.csv")

'Writing CSV headers
If Format = "GB"Then
ObjOutFile.WriteLine("Type,File Name,File Path,Size(GB), Owner")
Else
ObjOutFile.WriteLine("Type,File Name,File Path,Size(MB), Owner")
EndIf

'Call the GetFile function to get all files
GetFiles(Path)

'Close the output file ObjOutFile.Close
WScript.Echo("Completed")

Function GetFiles(FolderName)
OnErrorResumeNext
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjFiles = ObjFolder.Files

'Write all files to output files
ForEach ObjFileIn ObjFiles

If Format = "GB"Then
    Size=Round(((ObjFile.Size)/(1024*1024*1024)),2)
EndIf
If Format = "MB"Then
    Size=Round(((ObjFile.Size)/(1024*1024)),2)
EndIf
If Size > Int(data) Then
strFileName = ObjFolder & "\" & ObjFile.Name
WScript.Echo strFileName
Set objFileSecuritySettings = objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
WScript.Echo objSD.Owner.Name
If intRetVal = 0Then
   ObjOutFile.WriteLine(ObjFile.Type & "," & ObjFile.Name & "," & ObjFile.Path & "," & Size & "," & objSD.Owner.Domain & "\" & objSD.Owner.Name )
Else
   ObjOutFile.WriteLine(ObjFile.Type & "," & ObjFile.Name & "," & ObjFile.Path & "," & Size & ", Unable to find")
EndIf
EndIf
Next

'Getting all subfolders
Set ObjSubFolders = ObjFolder.SubFolders

ForEach ObjFolderIn ObjSubFolders
GetFiles(ObjFolder.Path)
Next
EndFunction

Script to find files and save in CSV format



This is a parameter based script. Syntaxes are given below.



cscript filesearch.vbs "path needs to search" size(MB or GB)

Example:
Below command will search list of file which are larger than 1 GB in "C:\Program Files" Path and stored in C:\Output.csv

cscript filesearch.vbs "c:\program files" 1GB

--------------------------------
Path
 = WScript.Arguments.Item(0)
Data1 = WScript.Arguments.Item(1)
Format = UCase(Right(Data1,2))
Data = Left(Data1,Len(Data1)-2)

If Format <> "GB"And Format <> "MB"Then
MsgBox"Data Format Error!!! Please correct"
WScript.Quit
EndIf
Dim fso
Dim ObjOutFile
'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Create an output file
Set ObjOutFile = fso.CreateTextFile("c:\Output.csv")

'Writing CSV headers
If Format = "GB"Then
ObjOutFile.WriteLine("Type,File Name,File Path,Size(GB)")
Else
ObjOutFile.WriteLine("Type,File Name,File Path,Size(MB)")
EndIf

'Call the GetFile function to get all files
GetFiles(Path)

'Close the output file ObjOutFile.Close
WScript.Echo("Completed")

Function GetFiles(FolderName)
OnErrorResumeNext
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjFiles = ObjFolder.Files

'Write all files to output files
ForEach ObjFileIn ObjFiles

If Format = "GB"Then
    Size=Round(((ObjFile.Size)/(1024*1024*1024)),2)
EndIf
If Format = "MB"Then
    Size=Round(((ObjFile.Size)/(1024*1024)),2)
EndIf
WScript.Echo FolderName
If Size > Int(data) Then
ObjOutFile.WriteLine(ObjFile.Type & "," & ObjFile.Name & "," & ObjFile.Path & "," & Size)
EndIf
Next

'Getting all subfolders
Set ObjSubFolders = ObjFolder.SubFolders

ForEach ObjFolderIn ObjSubFolders
GetFiles(ObjFolder.Path)
Next


EndFunction

Note: Script is only modified by me as per my requirement.