Many ways to skin a cat (or write a script)
I wanted to share with you another small example of how there are many ways to do things in PowerCLI. I wrote a post a while back about How to Speed Up Your PowerCLI Queries and there I came to the conclusion that not always is using Get-View faster.
I came across a case that a customer had a snapshot that was taken (never mind the reason) on all the VM’s and this snapshot is removed with a script thereafter.
They wanted to track the number of commitments left to complete.
So one way was
$a = get-vm | Get-Snapshot -Name "Thursday Backup"
Write-Host ""
Write-Host "$(Get-Date -Format hh:mm) - There are still $($a.count) Snapshots left"
Write-Host ""
and that to complete this gave this result
[12:17:42 PM] ~> measure-command {$a = get-vm | Get-Snapshot –Name
"Thursday Backup" ; Write-Host "";
Write-Host "$(Get-Date -Format HH:mm) - There are still $($a.count) Snapshots left"; Write-Host ""}
12:21 - There are still x Snapshots left
Days : 0
Hours : 0
Minutes : 3
Seconds : 41
Milliseconds : 410
Ticks : 2214108194
TotalDays : 0.00256262522453704
TotalHours : 0.0615030053888889
TotalMinutes : 3.69018032333333
TotalSeconds : 221.4108194
TotalMilliseconds : 221410.8194
But there is a quicker way to do this.
Function Get-Snapsleft {
$a = Get-View -ViewType Virtualmachine -Property Snapshot | % {
$_.Snapshot | % {
$($_.RootSnapshotList)
}
}
$b = $a | ? {$_.Name -eq "Thursday Backup" }
Write-Host ""
Write-Host "$(Get-Date -Format HH:mm) - There are still $($b.count) Snapshots left"
Write-Host ""
$a=$b=$null
}
And how long did this take?
[12:21:57 PM] ~> Measure-Command {Get-Snapsleft}
12:26 - There are still x Snapshots left
Days : 0
Hours : 0
Minutes : 0
Seconds : 2
Milliseconds : 359
Ticks : 23590940
TotalDays : 2.73043287037037E-05
TotalHours : 0.000655303888888889
TotalMinutes : 0.0393182333333333
TotalSeconds : 2.359094
TotalMilliseconds : 2359.094
That is one heck of a difference….
The technique to speed this up I took from mattboren over here..
Check your scripts, see if you can improve them – sometimes you might be surprised as to what you can achieve.