Looks like the Get-VM is not passing any virtualmachine objects to the Get-Stat cmdlet.
Are you connected to a vSphere server ?
Does 'Get-VM' return anything ?
To export to a CSV, place the code in a call code block and pipe that to the Export-Csv cmdlet.
Something like this
$start= (Get-Date).AddDays(-$daysBack)
&{Get-VM|
Get-Stat-Stat$stat-Start$start-ErrorActionSilentlyContinue|
Group-Object-Property {$_.Entity.Name} |%{
$diskMax=$_.Group|where {$_.MetricID-eq"disk.usage.average"} |
Measure-Object-PropertyValue-Average|Select-ExpandPropertyAverage
$netMAx=$_.Group|where {$_.MetricID-eq"net.usage.average"} |
Measure-Object-PropertyValue-Average|Select-ExpandPropertyAverage
$lastConnect=Get-VIEvent-Entity$_.Group[0].Entity-Start$start-MaxSamples ([int]::MaxValue) |
where {$_-is [VMware.Vim.VmRemoteConsoleConnectedEvent]} |
Sort-Object-PropertyCreatedTime-Descending|
Select-First1-ExpandPropertyCreatedTime
if($netMax-le$tgtNetMax-and$diskMax-le$tgtDiskMax-and$lastConnect){
$_| Select@{N="VM";E={$_.Value}},@{N="Disk Max";E={$diskMax}},@{N="Net Max";E={$netMax}}
@{N="Start date";E={$start}}
}
}} |
Export-Csv C:\report.csv -NoTypeInformation -UseCulture