PowerCLI

 View Only
Expand all | Collapse all

get-stat monthly report

  • 1.  get-stat monthly report

    Posted Jul 24, 2008 12:49 PM

    Hi,

    I'm trying to script the stats on a monthly basis. I'm using the below script,

    Get-Stat -Entity (Get-Cluster -Name x) -start (get-date).AddDays(-30) -Finish (Get-Date) -MaxSamples 1000 -stat cpu.usagemhz.average | Export-Csv -Path c:\test.csv

    It outputs based on time with 30 min interval.

    Is it possible to get it as a single value for a month as it shows in VC ??

    Also can we get the Max value reached in the cluster for the particular month.

    Hope my question is clear!!!!!

    Thanks



  • 2.  RE: get-stat monthly report

    Posted Jul 24, 2008 04:44 PM

    Sure, you can use the Measure-Object cmdlet for that.

    This will give you the maximum value for the period you are measuring

    Get-Stat -Entity (Get-Cluster -Name x) -start (get-date).AddDays(-30) -Finish (Get-Date) -MaxSamples 1000 -stat cpu.usagemhz.average | `
    Measure-Object -property Value  -maximum | select Maximum | Out-Default
    

    With the Measure-Object you can get the maximum, minimum, average and the sum.



  • 3.  RE: get-stat monthly report

    Posted Jul 25, 2008 11:04 AM

    Thanks LucD. That helped. I'm trying to put it in a proper format for all the cluster in my environment,

    $clust = Get-Cluster

    foreach($clu in $clust)

    {Get-Stat -Entity ($clu) -start (get-date).AddDays(-30) -Finish (Get-Date) -MaxSamples 10000 -stat cpu.usagemhz.average | Measure-Object -Property value -Average -Maximum | select $clu.name, average, maximum | Out-File -Append c:\g.csv}

    out-file doesnt format that correctly.. I'm not sure how to use export-csv cmdlet in this scenario.

    Also can i add the memory avg & max value along with CPU values in the same report. My report should look like

    ClusterName Memory Max Avg CPU Max Avg

    Could anyone guide me to do that.

    Thanks



  • 4.  RE: get-stat monthly report
    Best Answer

    Posted Jul 25, 2008 11:39 AM

    This should do what you want.

    $allclust = @()
    $clust = Get-Cluster
    
    foreach($clu in $clust){
      $clusstat = "" | Select ClusterName, MemMax, MemAvg, CPUMax, CPUAvg
      $clusstat.ClusterName = $clu.name
      
      $statcpu = Get-Stat -Entity ($clu) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
    	       -MaxSamples 10000 `
    		   -stat cpu.usagemhz.average
      $statmem = Get-Stat -Entity ($clu) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
    	       -MaxSamples 10000 `
    		   -stat mem.usage.average
    
      $cpu = $statcpu | Measure-Object -Property value -Average -Maximum
      $mem = $statmem | Measure-Object -Property value -Average -Maximum
      
      $clusstat.CPUMax = $cpu.Maximum
      $clusstat.CPUAvg = $cpu.Average
      $clusstat.MemMax = $mem.Maximum
      $clusstat.MemAvg = $mem.Average
      
      $allclust += $clusstat
    }
    
    $allclust | `
      select ClusterName, MemMax, MemAvg, CPUMax, CPUAvg | `
      Export-Csv "c:\g.csv" -noTypeInformation
    



  • 5.  RE: get-stat monthly report

    Posted Jul 25, 2008 12:21 PM

    Thanks LucD. You got me exactly what i was looking for. Amazing



  • 6.  RE: get-stat monthly report

    Posted Jul 29, 2009 12:44 PM

    Luc,

    Is there a way to make this report work for vms instead of the cluster? I am looking to report on average CPU and Memory utilization for vms over a month period. I would like to output to either csv or html. Any ideas?

    Thanks,

    Marc



  • 7.  RE: get-stat monthly report

    Posted Jul 29, 2009 01:30 PM

    Sure, shouldn't be too hard.

    Try something like this

    $allvms = @()
    $vms = Get-Vm
    
    foreach($vm in $vms){
      $vmstat = "" | Select VmName, MemMax, MemAvg, CPUMax, CPUAvg
      $vmstat.VmName = $vm.name
      
      $statcpu = Get-Stat -Entity ($vm) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
    	       -MaxSamples 10000 `
    		   -stat cpu.usagemhz.average
      $statmem = Get-Stat -Entity ($vm) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
    	       -MaxSamples 10000 `
    		   -stat mem.usage.average
    
      $cpu = $statcpu | Measure-Object -Property value -Average -Maximum
      $mem = $statmem | Measure-Object -Property value -Average -Maximum
      
      $vmstat.CPUMax = $cpu.Maximum
      $vmstat.CPUAvg = $cpu.Average
      $vmstat.MemMax = $mem.Maximum
      $vmstat.MemAvg = $mem.Average
      
      $allvms += $vmstat
    }
    
    $allvms | `
      select VmName, MemMax, MemAvg, CPUMax, CPUAvg | `
      Export-Csv "c:\VMs.csv" -noTypeInformation
    



  • 8.  RE: get-stat monthly report

    Posted Jul 30, 2009 03:10 PM

    Thanks LucD! Huge help! One more question for you? Is there anyway to gather this data for work hours only? Say 9am-5pm? I think the 24 hour period may skew the data a bit being that most of the vms are sitting idle over night. I would love to pinpoint this data to work hours.

    Thanks,

    Marc



  • 9.  RE: get-stat monthly report

    Posted Jul 30, 2009 04:07 PM

    I'm afraid that is not possible with the Get-Stat cmdlet itself, nor with the underlying QueryPerf method from the SDK.

    You could get all your statistical data and then use a Select-Object or an If-Then-Else construct on the Timestamp property to filter out the data you want.



  • 10.  RE: get-stat monthly report

    Posted Aug 25, 2009 05:17 PM

    Luc.. that was superb!

    Question:

    How do I change the syntax for the date period?

    This subroutine:

    -start (get-date).AddDays(-30) `
    -Finish (Get-Date) `

    My intent is to go back 30 days at a time.. If I can go perhaps start and finish dates per calender 30 days..

    aug, july, june etc.

    As is it runs date executed script minus 30 days.

    Merci! Thanks!

    -Vuong

    p.s. also I guess it is one vcenter at a time. I tried to connect-viserver to multiple vcenters, but the ouput wasn't there.

    I assume it was the output file doesn't append.



  • 11.  RE: get-stat monthly report

    Posted Aug 25, 2009 06:39 PM

    With a bit of conversion you could use the actual calendar months.

    The following script shows you the last 12 calendar months.

    $thisMonth = [datetime](Get-Date -Format "y")
    12..1 | %{
    	$from = $thisMonth.AddMonths(- $_)
    	$to = $thisMonth.AddMonths(- $_ + 1).AddDays(-1)
    	
    }
    

    If you use the $from in the -Start parameter and the $to in the -Finish parameter you can pull reports over the last 12 calendar months.



  • 12.  RE: get-stat monthly report

    Posted Aug 25, 2009 07:38 PM

    Hmm

    I tried (still learning) to modify the code:

    $allclust = @()

    $clust = Get-Cluster

    foreach($clu in $clust){

    $clusstat = "" | Select ClusterName, MemMax, MemAvg, CPUMax, CPUAvg

    $clusstat.ClusterName = $clu.name

    $thisMonth = datetime(Get-Date -Format "y")

    12..1 | %{

    $from = $thisMonth.AddMonths( - $_)

    $to = $thisMonth.AddMonths( - $_ + 1).AddDays(-1)

    }

    $statcpu = Get-Stat -Entity ($clu) `

    -start (get-date).AddDays(-30) `

    -Finish (Get-Date) `

    -MaxSamples 10000 `

    -stat cpu.usagemhz.average

    $statmem = Get-Stat -Entity ($clu) `

    -start (get-date).AddDays(-30) `

    -Finish (Get-Date) `

    -MaxSamples 10000 `

    -stat mem.usage.average

    $cpu = $statcpu | Measure-Object -Property value -Average -Maximum

    $mem = $statmem | Measure-Object -Property value -Average -Maximum

    $clusstat.CPUMax = $cpu.Maximum

    $clusstat.CPUAvg = $cpu.Average

    $clusstat.MemMax = $mem.Maximum

    $clusstat.MemAvg = $mem.Average

    $allclust += $clusstat

    }

    $allclust | `

    select ClusterName, MemMax, MemAvg, CPUMax, CPUAvg | `

    Export-Csv "c:\g.csv" -noTypeInformation

    But I got a syntax error:

    The term 'datetime' is not recognized as a cmdlet, function, operable program, or script fil

    again.

    At C:\Documents and Settings\phamv\Desktop\clusterstats2.ps1:7 char:22

    + $thisMonth = datetime <<<< (Get-Date -Format "y")

    + CategoryInfo : ObjectNotFound: (datetime:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

    You cannot call a method on a null-valued expression.

    At C:\Documents and Settings\phamv\Desktop\clusterstats2.ps1:9 char:30

    + $from = $thisMonth.AddMonths <<<< ( - $_)

    + CategoryInfo : InvalidOperation: (AddMonths:String) [], RuntimeException

    + FullyQualifiedErrorId : InvokeMethodOnNull



  • 13.  RE: get-stat monthly report

    Posted Aug 25, 2009 08:47 PM

    That's a problem of the forum sw that has problems with square brackets.

    The line should read: $thisMonth = \[datetime\](Get-Date -Format "y").

    But the way you inserted my sample code in the script won't work.

    I gave those last lines as an example of how to get the actual start and finish dates for the last 12 calendar months.

    Attached (to avoid the square brackets problem) a script that gets the report for the previous calendar month.

    I hope this clarifies a bit what I was trying to show.



  • 14.  RE: get-stat monthly report

    Posted Mar 29, 2010 07:35 PM

    LucD

    sorry to be so dense. I haven't had a chance to visit this topic in a while. I still don't understnad the formating syntax to get the last full 12 calendar months?

    Could you explain? Thank you very much.

    V



  • 15.  RE: get-stat monthly report

    Posted Mar 29, 2010 08:02 PM

    Sure, I'll give it a try

    This was the skeleton code to get the last 12 months

    $thisMonth = [datetime](Get-Date -Format "y")
    12..1 | %{
    	$from = $thisMonth.AddMonths(- $_)
    	$to = $thisMonth.AddMonths(- $_ + 1).AddDays(-1)
    	
    }
    

    The first line uses the Get-Date cmdlet with the Format parameter to get just the Month and the Year ("March 2010").

    Unfortunately that output is a string and we want a DateTime value for the rest of the script, so we cast the string to a DateTime object.

    And we store that in the $thisMonth variable.

    The cast will store the 1st day of the current month in the $thisMonth variable.

    Today this would give "Monday 01 March 2010 00:00:00".

    Then I start a loop where I count down from 12 to 1.

    The ".." operator indicates a range of integers between the two values left and right.

    In this case the result is 12 11 10 9 8 7 6 5 4 3 2 1.

    The "%" statement is an alias for the Foreach-Object cmdlet.

    In the code block that follows (the lines between the curly braces) the $_ variable represents the actual value.

    So this variable will get the values 12 11 10 9 8 7 6 5 4 3 2 1 respectively.

    We calculate the $from variable.

    We subtract a number of months (value in $_) from the DateTime object in $thisMonth. We do this with the AddMonths method that is available on a DateTime object.

    Remember the $thisMonth variable contained "Monday 01 March 2010 00:00:00" , so if we subtract 12 months we get "Sunday 01 March 2009 00:00:00".

    The $to variable is again calculated from the $thisMonth variable.

    We subtract $_ minus 1 month, which gives us "Wednesday 01 April 2009 00:00:00".

    But we want the last day of the previous month so we subtract 1 day with the AddDays method.

    And this gives us "Tuesday 31 March 2009 00:00:00".

    Since we do this for all the values of the range we get 12 start-end dates for the past 12 months.

    I hope this cleared it up a bit.

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 16.  RE: get-stat monthly report

    Posted Mar 29, 2010 08:39 PM

    That makes sense..except I get and error.. executing

    Missing expression after unary operator '-'.

    At C:\Documents and Settings\user\Desktop\xxxxx\powercli\scripts\report-last

    -2calendar-month.ps1:16 char:3

    + - <<<< start $from

    + CategoryInfo : ParserError: (-:String) [], ParseException

    + FullyQualifiedErrorId : MissingExpressionAfterOperator

    ====

    HUH?

    $thisMonth = (Get-Date -Format "y")

    12..1 | %{

    $from = $thisMonth.AddMonths(- $_ )

    $to = $thisMonth.AddMonths(- $_ +1).AddDays(-1)

    }

    =================



  • 17.  RE: get-stat monthly report

    Posted Mar 29, 2010 08:51 PM

    This is what I running...



  • 18.  RE: get-stat monthly report

    Posted Mar 30, 2010 05:30 AM

    If you want to split up a line over multiple lines in your script, you have to use the back-tick.

    Like this

    Get-VM `
    -Name "MyVM"
    

    Otherwise PowerShell considers the 2nd line as a seperate statement.

    That's why you get the "Missing expression after unary operator '-'." message. PowerShell considers the 2nd line "-start $from" as a new statement.

    The calls to the Get-Stat cmdlet should be inside the loop over the last 12 months. See the attached script.

    Btw there is in this case no need to use the MaxSamples parameter.

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 19.  RE: get-stat monthly report

    Posted Mar 29, 2010 09:06 PM

    Luc,

    The typecasting to datetime seems to work only if your computer uses the English language pack. I use Windows 7 Ultimate 64-bits with the Dutch language pack installed. Now I get an error with the typecasting. In English it works fine:

    [vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> [datetime] "March 2010"
    
    maandag 1 maart 2010 0:00:00
    
    
    [vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> 
    

    But if I use your code, I get an error:

    [vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> [datetime] (Get-Date -Format "y")
    Cannot convert value "maart 2010" to type "System.DateTime". Error: "De tekenreeks is niet herkend als een geldige Date
    Time. Index 0 begint met een onbekend woord."
    At line:1 char:11
    + [datetime] <<<<  (Get-Date -Format "y")
        + CategoryInfo          : NotSpecified: (:) [], RuntimeException
        + FullyQualifiedErrorId : RuntimeException
    
    [vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>
    

    I get the same error if I replace (Get-Date -Format "y") by it's value "maart 2010"

    vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> [datetime] "maart 2010"
    Cannot convert value "maart 2010" to type "System.DateTime". Error: "De tekenreeks is niet herkend als een geldige Date
    Time. Index 0 begint met een onbekend woord."
    At line:1 char:11
    + [datetime] <<<<  "maart 2010"
        + CategoryInfo          : NotSpecified: (:) [], RuntimeException
        + FullyQualifiedErrorId : RuntimeException
    
    [vSphere PowerCLI] C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>
    

    For people who don't understand Dutch, I will give a translation of the Dutch words in English:

    maandag = monday

    maart = March

    De tekenreeks is niet herkend als een geldige Date = The characterstring is not recognized as a valid Date

    Index 0 begint met een onbekend woord = Index 0 starts with an unknown word

    Luc, do you know if there is a way to use.NET typecasting in Dutch instead of English?

    Robert



  • 20.  RE: get-stat monthly report

    Posted Mar 30, 2010 06:23 AM

    Robert,

    That behaviour is, in my opinion, a PowerShell "feature".

    The "culture" concept is not implemented in all PowerShell features as thorough as it should be.

    Since you're using a Dutch PS version, the DateTime casting operator should be able to read the Dutch-formatted datetime string. But apparently it isn't.

    Have a look at Keith Hil's [Windows PowerShell 2.0 String Localization|

    http://keithhill.spaces.live.com/blog/cns!5A8D2641E0963A97!7132.entry] post.

    It contains an improved Using-Culture function. That could be a bypass for this problem.

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 21.  RE: get-stat monthly report

    Posted Mar 30, 2010 06:27 AM

    I found a way to get the beginning of the month in a language independent way:

    $Now = Get-Date
    $thisMonth = $Now.AddDays(1-$Now.Day).AddHours(-$Now.Hour).AddMinutes(-$Now.Minute).AddSeconds(-$Now.Second).AddMilliseconds(-$Now.Millisecond)
    

    Robert



  • 22.  RE: get-stat monthly report

    Posted Mar 30, 2010 06:33 AM

    As always, there are multiple ways to do something in PS.

    You could also just do

    $thisMonth = Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0
    

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 23.  RE: get-stat monthly report

    Posted Mar 30, 2010 06:42 AM

    Luc,

    your solution is nicer. And thanks for the link to Keith Hill's article. Very interesting.

    Robert



  • 24.  RE: get-stat monthly report

    Posted Aug 18, 2010 03:11 AM

    Luc,

    How would I go about getting this information on a per datastore basis?

    I'm looking to get disk utilization info for the last month. Need to know which VMs are busiest on each datastore. This would be either to run against all datastores of an esx host / cluster or would be even better if there was an option to put in a specific datastore as an argument. I hope this makes sense.

    Thanks



  • 25.  RE: get-stat monthly report

    Posted Aug 18, 2010 02:05 PM

    If I understood your question correctly, you want to see the top-5 virtual disk users for a specific datastore ?

    PS: perhaps it would be better if you created a new thread for your question.

    ____________

    Blog: LucD notes

    Twitter: lucd22



  • 26.  RE: get-stat monthly report

    Posted Aug 18, 2010 03:16 PM

    Ok new thread created.



  • 27.  RE: get-stat monthly report

    Posted Apr 15, 2011 03:15 PM

    Hello,

    I have to retrieve stats of VMs for last the 30 days on a vCenter.

    I used this code:


    Connect-VIServer -Server -Protocol https -User -Password

    $allvms = @()
    $vms = Get-Vm

    foreach($vm in $vms){
      $vmstat = "" | Select VmName, MemMax, MemAvg, CPUMax, CPUAvg, DiskMax, DiskAvg
      $vmstat.VmName = $vm.name
     
      $statcpu = Get-Stat -Entity ($vm) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat cpu.usagemhz.average
      $statmem = Get-Stat -Entity ($vm) `
               -Start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat mem.consumed.average
      $statdisk = Get-Stat -Entity ($vm) `
               -Start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat disk.usage.average


      $cpu = $statcpu | Measure-Object -Property value -Average -Maximum
      $mem = $statmem | Measure-Object -Property value -Average -Maximum
      $disk = $statdisk | Measure-Object -Property value -Average -Maximum

     
      $vmstat.CPUMax = $cpu.Maximum
      $vmstat.CPUAvg = $cpu.Average
      $vmstat.MemMax = $mem.Maximum
      $vmstat.MemAvg = $mem.Average
      $vmstat.DiskMax = $disk.Maximum
      $vmstat.DiskAvg = $disk.Average
     
      $allvms += $vmstat
    }

    $allvms | Select VmName, MemMax, MemAvg, CPUMax, CPUAvg, DiskMax, DiskAvg | Export-Csv "c:\VMs.csv" -noTypeInformation -UseCulture

    It seems working, (although I have some difficulty to understand how to use the MaxSample and if I must use it).

    But I also have to retrieve the host name, provisioned and used space on HDDs, Guest OS name and CPU count.. and I have some difficulties, I am a beginner in PowerShell scripting, C# and VMware SDK (I'm a student :smileyhappy: ).

    Can you help me ?

    Thanks.



  • 28.  RE: get-stat monthly report

    Posted Apr 15, 2011 05:34 PM

    I have added the request features host name, provisioned and used space on HDDs, Guest OS name and CPU count to your script. You don't need the select cmdlet on the last line, because you selected all the properties and that is the default, so I removed that select cmdlet.

    You can use the -MaxSamples parameter of the Get-Stat cmdlet to specify the maximum number of samples for each statistic. E.g. if you only want the latest value, you can use -MaxSamples 1.

    Connect-VIServer -Server vCenter -Protocol https -User -Password 
    
    $allvms = @()
    $vms = Get-Vm
    
    foreach($vm in $vms){
      $vmstat = "" | Select VmName, GuestName, NumCPU, ProvisionedSpaceGB, UsedSpaceGB, VmHost, MemMax, MemAvg, CPUMax, CPUAvg, DiskMax, DiskAvg 
      $vmstat.VmName = $vm.name
      $vmstat.GuestName = $vm.Guest.HostName 
      $vmstat.NumCPU = $vm.NumCPU
      $vmstat.ProvisionedSpaceGB = $vm.ProvisionedSpaceGB
      $vmstat.UsedSpaceGB = $vm.UsedSpaceGB
      $vmstat.VmHost = $vm.VMHost
      
      $statcpu = Get-Stat -Entity ($vm) `
               -start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat cpu.usagemhz.average
      $statmem = Get-Stat -Entity ($vm) `
               -Start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat mem.consumed.average
      $statdisk = Get-Stat -Entity ($vm) `
               -Start (get-date).AddDays(-30) `
               -Finish (Get-Date) `
                 -stat disk.usage.average
    
    
      $cpu = $statcpu | Measure-Object -Property value -Average -Maximum
      $mem = $statmem | Measure-Object -Property value -Average -Maximum
      $disk = $statdisk | Measure-Object -Property value -Average -Maximum
    
      
      $vmstat.CPUMax = $cpu.Maximum
      $vmstat.CPUAvg = $cpu.Average
      $vmstat.MemMax = $mem.Maximum
      $vmstat.MemAvg = $mem.Average
      $vmstat.DiskMax = $disk.Maximum
      $vmstat.DiskAvg = $disk.Average
      
      $allvms += $vmstat
    }
    
    $allvms | Export-Csv "c:\VMs.csv" -noTypeInformation -UseCulture
    
    

    Regards, Robert



  • 29.  RE: get-stat monthly report

    Posted Apr 18, 2011 01:46 PM

    Thank you very much!

    It seems to be not to difficult finaly. :smileyhappy:

    It work like a charm, thanks again!

    I have an another question, I have to generate  graphics with max/avg stats for each VMs on each 30 days. Is it possible  to retrieve samples for each days ?



  • 30.  RE: get-stat monthly report

    Posted Apr 19, 2011 01:55 PM

    The next script gives you average and maximum performance statistics per virtual machine for the last 30 days for each day:

    Function Get-AverageStatPerDay {
      param($vm,$NrOfdays,$Stat)
      
      $Today = Get-Date
      Get-Stat -Entity ($vm) `
               -start ($Today).AddDays(-$NrOfDays) `
               -Finish ($Today) `
               -stat $Stat | `
        ForEach-Object {
          $MetricId = $_.MetricId
          $Unit = $_.Unit
          $_ | `
            Select-Object -Property Description,Entity,EntityId,Instance,IntervalSecs,MetricId,Timestamp,Unit,Value,@{N="Date";E={$_.TimeStamp.Date.ToShortDateString()}}
        } | `
          Group-Object -Property Date | `
          Select-Object -Property @{N="VM";E={$vm.Name}},
            @{N="MetricId";E={$MetricId}},
            @{N="Date";E={$_.Name}},
            @{N="Value";E={($_.Group | Measure-Object -Property Value -Average).Average}},
            @{N="Unit";E={$Unit}}
    }     
    
    Function Get-MaximumStatPerDay {
      param($vm,$NrOfdays,$Stat)
      
      $Today = Get-Date
      Get-Stat -Entity ($vm) `
               -start ($Today).AddDays(-$NrOfDays) `
               -Finish ($Today) `
               -stat $Stat | `
        ForEach-Object {
          $MetricId = $_.MetricId
          $Unit = $_.Unit
          $_ | `
            Select-Object -Property Description,Entity,EntityId,Instance,IntervalSecs,MetricId,Timestamp,Unit,Value,@{N="Date";E={$_.TimeStamp.Date.ToShortDateString()}}
        } | `
          Group-Object -Property Date | `
          Select-Object -Property @{N="VM";E={$vm.Name}},
            @{N="MetricId";E={$MetricId}},
            @{N="Date";E={$_.Name}},
            @{N="Value";E={($_.Group | Measure-Object -Property Value -Maximum).Maximum}},
            @{N="Unit";E={$Unit}}
    }     
    
    Get-VM | ForEach-Object {
      $vm = $_
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.average
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.maximum
    }
    
    



  • 31.  RE: get-stat monthly report

    Posted Apr 21, 2011 08:11 AM

    Thanks a lot.



  • 32.  RE: get-stat monthly report

    Posted May 11, 2011 10:16 AM

    Hello,

    I have some trouble to export the output into a csv.

    When it's "work", it only write this in the file:

    "PowerState","Version","Description","Notes","Guest","NumCpu","MemoryMB","HardDisks","NetworkAdapters","UsbDevices","CDDrives","FloppyDrives","Host","HostId","VMHostId","VMHost","VApp","FolderId","Folder","ResourcePoolId","ResourcePool","PersistentId","UsedSpaceGB","ProvisionedSpaceGB","DatastoreIdList","HARestartPriority","HAIsolationResponse","DrsAutomationLevel","VMSwapfilePolicy","VMResourceConfiguration","CustomFields","ExtensionData","Id","Name","Uid"
    "PoweredOff","v7","","","Windows_XP_SP3_x86:","1","512","VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.HardDisk[]","VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.NetworkAdapter[]","VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.UsbDevice[]","VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.CDDrive[]","VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.FloppyDrive[]","esx4.na.cetsi.corp","HostSystem-host-9","HostSystem-host-9","esx4.na.corp",,"Folder-group-v34","Template","ResourcePool-resgroup-8","Resources","5014693c-280c-1f71-5a9a-1a55b486ae49","1,443538","20,50018","System.String[]","ClusterRestartPriority","AsSpecifiedByCluster","AsSpecifiedByCluster","Inherit","CpuShares:Normal/1000 MemShares:Normal/5120","VMware.VimAutomation.ViCore.Impl.V1.Util.ReadOnlyDictionary`2[System.String,System.String]","VMware.Vim.VirtualMachine","VirtualMachine-vm-32","Windows_XP_SP3_x86","/VIServer=administrateur@vcenter01:443/VirtualMachine=VirtualMachine-vm-32/"

    Or I get an error like this one:

    Select-Object : Impossible de convertir System.Management.Automation.PSObject e
    n l'un des types suivants {System.String, System.Management.Automation.ScriptBl
    ock}.
    Au niveau de ligne : 10 Caractère : 9
    +   Select <<<<  $allvms | Export-Csv "c:\VMsGraph.csv" -noTypeInformation -Use
    Culture
        + CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupport
       edException
        + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Co
       mmands.SelectObjectCommand

    I tried to use several commands like:

    $allvms = @()
    Get-VM | ForEach-Object {
      $vm = $_
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.average
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.maximum
     
        $allvms += $vm

      Select $allvms | Export-Csv "c:\VMsGraph.csv" -noTypeInformation -UseCulture
    }

    or

    Select $vm | Export-Csv "c:\VMsGraph.csv" -noTypeInformation -UseCulture

    Select $allvms | Export-clixml c:\test.xml | import-clixml c:\test.xml | export-csv c:\test.csv

    I don't understand why it don't write all the stats shown in the powershell window.



  • 33.  RE: get-stat monthly report

    Posted May 11, 2011 11:28 AM

    To export the output to a .csv file, you can pipe the output of the script in my previous post to a Export-Csv cmdlet. Like:

    Get-VM | ForEach-Object {
      $vm = $_
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.average
      Get-AverageStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.average
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat cpu.usagemhz.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat mem.consumed.maximum
      Get-MaximumStatPerDay -vm $vm -NrOfDays 30 -Stat disk.usage.maximum
    } | Export-Csv "C:\VMsGraph.csv" -noTypeInformation -UseCulture
    
    
    



  • 34.  RE: get-stat monthly report

    Posted Jun 06, 2011 08:37 AM

    Thanks it works great :smileyhappy:

    I have edited the script to retrieve the stats of a cluster if someone need it.

    Function Get-AverageStatPerDay {
      param($clu,$NrOfdays,$Stat)
     
      $Today = Get-Date
      Get-Stat -Entity ($clu) `
               -start ($Today).AddDays(-$NrOfDays) `
               -Finish ($Today) `
               -stat $Stat | `
        ForEach-Object {
          $MetricId = $_.MetricId
          $Unit = $_.Unit
          $_ | `
            Select-Object -Property Description,Entity,EntityId,Instance,IntervalSecs,MetricId,Timestamp,Unit,Value,@{N="Date";E={$_.TimeStamp.Date.ToShortDateString()}}
        } | `
          Group-Object -Property Date | `
          Select-Object -Property @{N="Cluster";E={$clu.Name}},
            @{N="MetricId";E={$MetricId}},
            @{N="Date";E={$_.Name}},
            @{N="Value";E={($_.Group | Measure-Object -Property Value -Average).Average}},
            @{N="Unit";E={$Unit}}
    }    

    Get-Cluster | ForEach-Object {
      $clu = $_
      Get-AverageStatPerDay -clu $clu -NrOfDays 30 -stat cpu.usagemhz.average
      Get-AverageStatPerDay -clu $clu -NrOfDays 30 -stat mem.consumed.average
    } | Export-Csv "C:\ClusterGraph.csv" -noTypeInformation -UseCulture

    I have an another question, sorry.. , is it possible to get the multipathing status, the used space, the snapshot space and the number of disks for a list of VM in only one script ?

    Thank you.