Some of useful VMware PowerCLI scripts added into VMware Sample Exchange

Recently while working on couple of customer cases, I had to write some useful vSphere PowerCLI scripts. I had submitted these scripts on VMware Sample Exchange, I thought to share on blog as well. If you haven’t still explored VMware Sample Exchange , please have your “My VMware” account created (Mandatory to have My VMware account to contribute or request) and enjoy the single pane of glass for VMware API samples across any product, any programming language and any platform (including CLIs). You can browse already existing samples as well as request new API sample that you are looking for. This is really cool site for learning VMware APIs, it is a must book-mark if you ask me. Here is the VMTN Sample Exchange community for more details.

Here we go for the PowerCLI scripts that I am talking about.

Below are the use-cases these script will help you on.

1. Report on vSphere compute cluster usage/capacity data on CPU, Memory and Storage.
2. Report on DRS VM-VM affinity rules associated with each VMs in the cluster.
3. Solution 1 : Report on VMs with “multi-writer” flag enabled.
4. Solution 2: Report on VMs with “multi-writer” flag enabled.

1. Report on vSphere compute cluster usage/capacity data on CPU, Memory and Storage. Sample exchange script location


< #
.SYNOPSIS Getting Cluster usage/capacity data on CPU, Memory and Storage 
.NOTES  Author:  Vikas Shitole
.NOTES  Site:    www.vThinkBeyondVM.com
.NOTES  Reference: http://vthinkbeyondvm.com/category/powercli/
.NOTES Please add the vCenter server IP/credentails as per your environment
#>

Connect-VIServer -Server 10.92.166.82 -User Administrator@vsphere.local -Password xyz!23

$report = @()

Write-host "Report Generation is in Progress..."

foreach ($cluster in Get-Cluster   ){

  $row = '' | select ClusterName,CpuCapacity , CpuUsed, MemCapacity,MemUsed ,StorageCapacity,StorageUsed
$cluster_view = Get-View ($cluster)
$resourceSummary=$cluster_view.GetResourceUsage()
$row.ClusterName =$cluster_view.Name
$row.CpuCapacity =$resourceSummary.CpuCapacityMHz
$row.CpuUsed =$resourceSummary.CpuUsedMHz
$row.MemCapacity =$resourceSummary.MemCapacityMB
$row.MemUsed =$resourceSummary.MemUsedMB
$row.StorageCapacity =$resourceSummary.StorageCapacityMB
$row.StorageUsed =$resourceSummary.StorageUsedMB

$report += $row
}
$report | Sort  ClusterName | Export-Csv -Path "D:Clusterstats.csv" #Please change the CSV file location

Write-host "Report Generation is completed, please chekc the CSV file"		
	

2. Report on DRS VM-VM affinity rules associated with each VMs in the cluster. Sample Exchange script location


< #
.SYNOPSIS Getting DRS VM-VM affinity rules associated with each VMs in the cluster.
.NOTES  Author:  Vikas Shitole
.NOTES  Site:    www.vThinkBeyondVM.com
.NOTES  Reference: http://vthinkbeyondvm.com/category/powercli/ 
.NOTES Please add the vCenter server IP/credetails as per your environment

#>

Connect-VIServer -Server 10.192.x.y -User Administrator@vsphere.local -Password xyz!23

$clusterName = "BLR" #Your cluster name
$cluster = Get-Cluster -Name $clusterName
$vms = Get-View ($cluster| Get-VM)
$cluster_view = Get-View ($cluster)

$report = @()

Write-host "Report Generation is in Progress..."

foreach ($vm in $vms  ){

  $row = '' | select VMName, Rules
  $rules=$cluster_view.FindRulesForVm($vm.MoRef)
  $ruleNameArray=" "
  #There can be more than one rule assciated with single VM
  foreach($rule in $rules){
  $ruleNameArray+=$rule.Name
  $ruleNameArray+=","
  }
  $row.VMName =$vm.Name
  $row.Rules = $ruleNameArray
  $report += $row
  }
$report | Sort Name | Export-Csv -Path "D:VMsRules.csv" #Please change the CSV file location

Write-host "Report Generation is completed, please chekc the CSV file"
	
	

3. Solution 1 : Report on VMs with “multi-writer” flag enabled. Sample exchange script location

< #
.SYNOPSIS: This script first downloads all the VMX files (per host/cluster/datacenter/VC)at specified file location
.Once downloaded, it will scan each VMX file one by one to get "multi-writer" entry inside VMX
.Finally it will list all matching VMX file names into specified file location. 
.As it downloads all the VMX files, it is going to take more time, that should be fine. 
.It is all right to download the VMX file when VM is up and running.
.If name of the VM is changed, VMX file can be different from VM display name (visible from inventory). 
.There are 2 file locations you need to specify. 1. Directory where VMX file will be downloaded 2. Output file.

.NOTES  Author:  Vikas Shitole
.NOTES  Site:    www.vThinkBeyondVM.com
.NOTES  Reference: http://vthinkbeyondvm.com/category/powercli/ and https://communities.vmware.com/message/2269363#2269363
.NOTES Please add the vCenter server IP/credetails as per your environment
.NOTES Alternatively you can use this script where API properties are used. https://github.com/vThinkBeyondVM/vThinkBVM-scripts/blob/master/Powershell-PowerCLI/VMMultiWriterReport.ps1
#>


Write-host "Connecting to vCenter server.."
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false -DisplayDeprecationWarnings:$false -Scope User
Connect-VIServer -Server 10.192.67.143 -User administrator@vsphere.local -Password Admin!23

$tgtFolder = "C:\Temp\VMX\"  #Create this directory as per your environment
#$tgtString = 'scsi0:0.sharing="multi-writer"'
$tgtString = '"multi-writer"'
foreach ($vm in Get-VM ){

Get-VM -Name $vm.get_Name() | %{
  $dsName,$vmxPath = $_.ExtensionData.Config.Files.VmPathName.Split()
  $dsName = $dsName.Trim('[]')
  $ds = Get-Datastore -Name $dsName
  New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root "\" | Out-Null
  Copy-DatastoreItem -Item "DS:$vmxPath" -Destination $tgtFolder
  Remove-PSDrive -Name DS -Confirm:$false
}

}
Get-ChildItem -Path $tgtFolder -Filter "*.vmx" | Where {Get-Content -Path $_.FullName | Select-String -Pattern $tgtString} | Select Name | Out-File C:\test1.txt
Write-host "Execution is done... please check the file with all VMX file names."

# Below cmdlet can help to scan VMs per Datacenter/Datastore/Host/Cluster. Please modify the script as required. 

#$myDatacenter = Get-Datacenter -Name "MyDatacenter"
#Get-VM -Location $myDatacenter

#$myDatastore = Get-Datastore -Name "MyDatastore"
#Get-VM -Datastore $myDatastore

#$myHost=Get-VMHost -Name "HostName"
#Get-VM -Location $myHost

#$myCluster=Get-Cluster -Name "ClusterName"
#Get-VM -Location $myCluster

	

4. Solution 2 : Report on VMs with “multi-writer” flag enabled. Sample Exchange script location


< #
.SYNOPSIS: This script connects to the vCenter Server and prepares a report on All VMs with at-least one disk enabled with "Multi-Writer" sharing.
.Report will be generated as CSV file with "VM Name". This can be modified to add some more columns as needed
.VC IP/UserName/Password are hardcoded below, please change them as per your environment
.By default this script scans all the VMs/VMDK in the vCenter Server. It can be easily twicked to scan VM per cluster or host or datacenter

.NOTES  Author:  Vikas Shitole
.NOTES  Site:    www.vThinkBeyondVM.com
.NOTES  Reference: http://vthinkbeyondvm.com/category/powercli/
.NOTES Please add the vCenter server IP/credetails as per your environment

Alternate solution by scanning VMX file is here: https://github.com/vThinkBeyondVM/vThinkBVM-scripts/blob/master/Powershell-PowerCLI/VMMultiWriterReport2.ps1

#>

Write-host "Connecting to vCenter server.."
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false -DisplayDeprecationWarnings:$false -Scope User
Connect-VIServer -Server 10.192.x.y -User administrator@vsphere.local -Password xyz@123


$report = @()
Write-host "Report Generation is in Progress..."

foreach ($vm in Get-VM  ){
$view = Get-View $vm
$settings=Get-AdvancedSetting -Entity $vm
   if ($view.config.hardware.Device.Backing.sharing -eq "sharingMultiWriter" -or $settings.value -eq "multi-writer"){
   $row = '' | select Name
      $row.Name = $vm.Name
   $report += $row
   }
   
}
$report | Sort Name | Export-Csv -Path "D:MultiWriter.csv" #Please change the CSV file location

Write-host "Report is generated successfully, please check the CSV file at specified location"

#If you want to generate report per Datacenter/Datastore/Host/Cluster, modify script using below code.

#$myDatacenter = Get-Datacenter -Name "MyDatacenter"
#Get-VM -Location $myDatacenter

#$myDatastore = Get-Datastore -Name "MyDatastore"
#Get-VM -Datastore $myDatastore

#$myHost=Get-VMHost -Name "HostName"
#Get-VM -Location $myHost

#$myCluster=Get-Cluster -Name "ClusterName"
#Get-VM -Location $myCluster

55 thoughts on “Some of useful VMware PowerCLI scripts added into VMware Sample Exchange

  1. I know its difficult, but you have shown it to be too easy to do. Making simple steering wheel covers out of clothes or yarns are very exciting and a very satisfying craft. Thanks a lot for your guide.

    1. I’m sorry, I’m not interested http://silverdaddies.fun/ silverdaddies Billy Burrows of Annuity Line, a broker, said it was “always difficult” to predict future annuity rates but for them to repeat the rise they had already shown this year the 15-year gilt yield would have to increase from its current level of around 3.25pc to more than 4.25pc. “In the current climate this seems unlikely,” he said.

    2. this post is fantastic http://silverdaddies.fun/ silverdaddies Rising stockpiles can be a good sign for the economy because they suggest companies expect greater sales. Greater inventory building also means businesses ordered more goods, boosting factory production and economic growth. And higher sales mean that companies are less likely to be stuck with excess goods.

    3. Another year http://madthumbs.fun/ madthumbs.com Obama’s speech is one of a series focused on spurring fastereconomic growth in the middle of a still tepid recovery. Hiscampaign-like tour is meant to help set the stage for the 2014congressional elections and, more immediately, lay out his viewsahead of an expected budget battle in Washington this fall.

    4. Do you know each other? http://xtube.in.net/ xtube Illinois Rep. John Bradley, a Democrat from down stateMarion, Ill., introduced legislation on Friday that would giveADM a 10 percent discount on utility taxes for up to 30 years ifit does not move its head office out of state. ADM also wouldreceive credits on some income taxes.

    5. Do you have any exams coming up? http://fittor.top/ sma fittor
      As the New York session began, the dollar’s strength againstthe euro was blunted by a report that showed U.S. producerprices were flat in July, pointing to very little inflationarypressure, which could add to worries at the Fed that inflationis running too low. The dollar fell against the yen.

    6. Recorded Delivery http://femjoy.in.net/ femjoy models This doesn’t bode well, but once you start using the BlackBerry Q5 things do get better. The one thing that has always made BlackBerry devices stand out from the competition is their keyboards. What’s here is good – but it is not great.

    7. How much is a First Class stamp? http://keandra.in.net/ keandra porn That’s because there are no serious talks going on right now on the budget and deficit between the White House and Congress, Bixby explained, adding he thinks the report would have had more impact in August or early September.

    8. I’m sorry, she’s http://fittor.fun gamla fittor “The consistency of these findings suggests that these fatty acids are involved in prostate tumorigenesis and recommendations to increase long-chain omega-3 fatty acid intake, in particular through supplementation, should consider its potential risks,” the US study said.

    9. I want to make a withdrawal http://xtube.in.net/ tube x
      It said: “The remuneration committee decided to award a terminal bonus of 49 per cent of his salary and to defer 50 per cent of the bonus until the successful completion of the sale of East Village to QDD.”

    10. In tens, please (ten pound notes) http://xnxx.in.net/ xnxx.com Still, the questions around Penney’s future suggest morevolatility ahead. Its credit default swaps, insurance against adefault, price a nearly 65 percent default probability in fiveyears and 85 percent over 10 years, according to data fromMarkit. For some bond mavens, that’s just too much risk to takeon.

    11. I’d like to cancel this standing order http://xvedio.in.net/ sexvedio Tests were also carried out on a girl taken into care in Dublin, although they have concluded that she was living with her biological parents. Police had initially not been persuaded by the birth certificate and passport provided by the family, reports said.

    12. Could you please repeat that? http://xvedio.in.net/xvidoes/ xvidoes Duty-free access to Western markets and low wages have helped make Bangladesh the world’s second-largest apparel exporter after China, with 60 percent of clothes going to Europe and 23 percent to the United States.

    13. Will I have to work on Saturdays? http://fittor.fun sma fittor
      So far, only seven of the 32 NFL teams have been on the series, which airs on HBO: Dallas Cowboys (twice), Cincinnati Bengals (twice), New York Jets, Baltimore Ravens, Miami Dolphins, Jacksonville Jaguars, and Kansas City Chiefs.

    14. I have my own business http://tubegalore.in.net/ tubegalore porn Prosecutors, who have argued that Manning was an arrogant soldier who aided al Qaeda militants and harmed the United States with the release of the documents, will have an opportunity to rebut the defense case on Friday.

    15. When do you want me to start? http://rockettube.fun/ rokettube He fled French police in 1940 and met Ho Chi Minh in southwestern China before returning to rural northern Vietnam to recruit guerrillas for the Viet Minh, a forerunner to the southern insurgency later known as the Viet Cong.

    16. Can you hear me OK? http://madthumbs.fun/ mad thumbs In Iten, a small village at the heart of Kenya’s running revolution, athletes are reluctant to talk about doping with outsiders but the issue is a common topic of conversation among coaches, former runners and agents.

    17. How do you do? http://egotastic.in.net/ egotastic all stars In its statement, GDDKiA said it had shown flexibility with Alpine Bau, for example paying its sub-contractors directly when it was having financial problems, and bringing forward payments to Alpine. It said it worked successfully with many contractors, but the onus was on them to make sure that they bid realistically and carried out the work responsibly.

    18. I’ll send you a text http://ampland.fun/ mpland The drawback is it relies heavily on the Internet to run various services, so you’ll need to plan ahead if you’re looking to write that great masterpiece without access to Wi-Fi. That’s because the Chromebook doesn’t run Windows or Mac OS, like the majority of laptops. Rather, it uses Google’s Chrome OS system, which needs a steady Internet connection.

    19. Will I get paid for overtime? http://xxxnx.fun/ xlxx com “Milk powder pricing is a more imperative problem, as it’s baby food and concerns … families,” said Yale Zhang, managing director of Automotive Foresight (Shanghai) Co Ltd, a consultancy and industry research firm.

    20. I wanted to live abroad http://tiava.in.net/ tiava PRIVATE EQUITY firms in Asia Pacific are increasingly payingspecial dividends to themselves funded by refinancing debt ofthe businesses they own, a development that is being fuelled byfrothy credit markets and sluggish prospects for “exit” sales.

    21. magic story very thanks http://ampland.fun/ amp land July 31 (Reuters) – U.S. refiner Phillips 66 reported a quarterly profit below analysts’ estimates due tohigher costs for some of the U.S. crude oil it processes,sending its shares down 3 percent before the bell.

    22. I’m not sure http://lamalinks.fun/ lama nudes
      “He was a consummate author, creating the modern-daythriller, and was one of the most visionary storytellers of ourtime. I will miss him dearly and he will be missed by tens ofmillions of readers worldwide,” he added.

    23. I’m interested in http://xtube.in.net/ x tube Obviously, if there’s a spike in a certain type of crime — whether it’s robberies or felony assaults — we’re going to throw our impact officers and other resources into those areas. And, if need be, we will stop, question and frisk people.

    24. I’m doing an internship http://efukt.fun/ efukt.com If this continues, the total volume is likely to breach the12 bcf/d level by March 2014, raising questions about whatcriteria the department will use to decide which ones to approveand how many it intends to authorise in total.

    25. Thanks funny site http://ghettotube.in.net/ gettotube That’s hardly what Reese suggested in his WFAN radio interview Tuesday morning. It was then that the GM said JPP was “on schedule” and “looking good, he’s running around on the field a little bit.”

    26. Could you ask her to call me? http://silverdaddies.fun/ silverdaddies videos The outcome of Sunday’s vote is expected to be released on Sunday evening, said a statement from Unifor. The recently formed union is a merger of the Canadian Auto Workers and the Communications, Energy and Paperworkers Union of Canada.

    27. I never went to university http://xxxnx.world xnnx Ross informed the commission’s executive director Keith Kizer on Tuesday in an email that she was going on hiatus, saying: “I will be taking some time off from boxing but will keep in touch,” the story said. Ross’ boxing license expires at the end of the year, and there is speculation she either won’t renew it or the commission won’t grant her a new license, the story went on. Ross scored the fight 114-114 even though Mayweather dominated the less-experienced Alvarez. The other judges, Dave Moretti (116-112) and Craig Metcalfe (117-111), gave Mayweather a majority-decision victory.

    28. Would you like to leave a message? http://cedecspro.edu.co/ sudteen bbs DM actually stands for “Direct Message,” and it was because Booker — the quickly rising and single politician — responded to Lee’s flirtations with one such message that the duo found themselves in the spotlight.

    29. An accountancy practice http://xnxx.promo/ xnxx1 Perhaps the CD’s most left-field song — “FU” — luxuriates in solid retro-pop, referencing the tragic grandeur of Dusty Springfield. In songs like this, you can hear the richer qualities in Miley’s voice that might be nurtured in a less cynical project.

    30. Directory enquiries http://tiava.in.net/ tavia porn ** The Philippines is set to reject the lone bid itreceived on Thursday for a contract to build a $1.4 billionelevated railway extension project in the capital, the biggestinfrastructure project to be put on the auction block by theAquino government, a senior official said.

    31. Accountant supermarket manager http://thisav.fun/ thisav.com Judge Billisu Aliyu sentenced Shuaibu Abubakar, Salisu Ahmed, Umar Babagana-Umar and Mohamed Ali to life for their role in a bombing of the electoral commission offices in Suleja, a satellite town of Abuja, on April 8, 2011. That blast, a week before presidential elections, killed 16 people.

    32. Do you have any exams coming up? http://xnxx-xnxx.site/ xxnx com The four-time MVP kept up his record pace for touchdown passes, Matt Prater kicked a 28-yard field goal as time expired after an interception by Romo spoiled the first 500-yard game in Dallas history, and the Broncos stayed unbeaten with a 51-48 victory Sunday.

    33. Whereabouts are you from? http://xnxx.in.net/ xnxx videos “Those are the kinds of things that would put the Republican majority in the House in jeopardy and make it essentially impossible to win the majority in the Senate,” said Representative Tom Cole, a Republican moderate from Oklahoma.

    34. Would you like to leave a message? http://yuvututube.fun/ yuvutu porn
      In the footage on local channel Eastern Express a woman is heard saying above dramatic music that Putin has “brought the criticism of all international rights organizations on Russia” and is allowing corruption on “unimaginable scale”.

    35. International directory enquiries http://xnxx.promo/ xvxx All of which, you might say, is too good to be true. Does Johnson mind the mickey-taking that lampoons him as the right-on rocker? “Not really,” he says evenly. “Well, maybe for a little while … I don’t get it too much any more. The first years we started to do the [Ohana Foundation], in 2008, I almost felt like I was on the defensive – half the people were like, ‘OK, you’re doing this for your image, I get it.’ So they were trying to find holes in it all the time. But this time around it’s been great. We’ve been doing it for five years and we’re not really coming out and making a thing of it. I don’t feel like I have to explain it as much. And to be honest, it really does make my job easier to explain to my kids – it makes it feel a little more worth doing.”

    36. I’m happy very good site http://ghettotube.in.net/ gettotube “We will work with our Russian counterparts to reschedule the meeting. As we’ve long made clear it is imperative that we reach a comprehensive and durable political solution to the crisis in Syria,” said an official.

  2. in your first script, it’s not going to work well unless you have the varible $clusterName defined somewhere.

    1. Hi Aaron,
      Thanks for spotting. Looks like it was typo when I was converting this script to work for any number of clusters. I have removed the line “$cluster = Get-Cluster -Name $clusterName”, this is NOT required. Latest script should work just fine.

      1. Lost credit card http://al4a.fun/ al4a.com If you would like to apply for a visa WorkPermit.com can help. WorkPermit.com is a specialist visa consultancy with 25 years of experience dealing with visa applications. We can help with a wide range of visa applications to your country of choice. Please feel free to contact us for further details.

      2. Could you ask him to call me? http://xnxx.zone/ video xnxx An advisory from the U.S. National Hurricane Center saidKaren was downgraded to a tropical depression after its topsustained wind speeds dropped to 35 mph (55 kph), and alltropical storm warnings and watches were discontinued.

      3. Could I have an application form? http://thisav.fun/ thisavcom
        In recent decades, many municipalities have provided their workers with generous retirement benefits, both pensions and health coverage, often in lieu of pay increases. But this has created an unsustainable future burden for budgets that has only been exacerbated by the loss of real estate and other tax revenue in the financial crisis.

      4. A staff restaurant http://xnxx.in.net/ xnxx The deaths peaked in July, according to the Virginia Aquarium Stranding Response Team, and the number of dead dolphins is something that hasn’t been seen since 1987, when more than 750 carcasses washed ashore from New Jersey to Florida. The mass deaths lasted 18 months.

      5. Have you seen any good films recently? http://planetsuzy.fun/ planet suzy The TSA said 894 guns alone have been taken directly off passengers or from their carry-on bags during the first six months of this year, a 30 percent increase compared to the same period last year. (People are allowed to travel with guns in their checked luggage, but must tell the TSA ahead of time about their presence.)

      6. Sorry, I ran out of credit http://imagefap.in.net/ image fap porn Investors were mainly encouraged by its positive netinterest margins, Credit Suisse analysts said in a note. This ismainly due to its higher asset yield, strong fee income and areduction in its inter-bank assets, they added.

      7. I’d like to order some foreign currency http://xnxx.promo/ xnsxx By Monday evening, the emergency crews had finally reached the Musi-Cafe, a downtown bar near the epicenter of the blast. A band was performing there and the building was packed with people when the explosion occurred, eyewitnesses told Reuters.

      8. I live in London http://9taxi.in.net/ taxi9
        Companies that amass intellectual property portfolios but don’t manufacture products – dubbed “patent trolls” by critics – have come under increased regulatory scrutiny. President Barack Obama called for reforms in June and federal trade officials launched an investigation of patent aggregators’ impact on the U.S. economy.

  3. Nice Scripts
    I was wondering if there was a way to modify the Cluster Stats script to average the resource usage over a 7 day period?
    Thanks

  4. I’d like to pay this in, please http://www.nationwidenannies.com.au/ lolita art pics nudist “The acquisition of offensive capability would be a fundamental change in our defence policy, a kind of philosophical change,” said Marushige Michishita, a professor at the National Graduate Institute of Policy Studies.

  5. I’m training to be an engineer http://highlightconseil.com/ pink lolita incest pics At euronews we believe in the intelligence of our viewers and we think that the mission of a news channel is to deliver facts without any opinion or bias, so that the viewers can form their own opinion on world events.

  6. I live here http://apetitmascotas.com/ is nizagara safe Newhart’s long TV history includes the 1970s “The Bob Newhart Show,” “Newhart” in the 1980s and “Bob” in the ’90s and six previous nominations. His 1961 variety series “The Bob Newhart Show” earned a writing bid.

  7. I study here http://wallpapers.in.net wallpaper hp cantik Republicans additionally scrutinized Napolitano for her knowledge of the “Fast and Furious” gun-running operation, which resulted in an ATF agent’s murder. Critics also said that flaws in DHS communications may have allowed the Boston Marathon suspects to slip through the cracks.

  8. Very funny pictures http://xnxx.in.net/ xnxx tube But the 82-year-old, who has earned the nickname the “Sun king”, also appears to be favoring conservative politics as he has done in Britain and the United States, while reinvigorating an Australian political war that dates back as far as 1975 and the dismissal of then Labor prime minister Gough Whitlam.

  9. which can be referenced instead of the name parameters. This helps by cutting down on the amount of additional calls which are being made to translate a name into an ID value.

Leave a Reply

Your email address will not be published. Required fields are marked *