VMware Cloud Community
DZ1
Hot Shot
Hot Shot
Jump to solution

Sort-Object with a custom value

I'm trying to sort some VMs, but I want them sorted by the number of snapshots that they have.  I have tried a few things, I just know that I am missing something simple.  I'm only geting VMs with 3 or more snapshots, and then I want to sort by that number.  I have played around with the script, so I have comments, and then I try something else, and comment something else out.

Here is what I have tried:

Get-VM | where { ($_ | Get-Snapshot).count -gt 2 } | sort -Descending -Property @{N=$i; E={ ($_ | Get-Snapshot).count  }  } | foreach {
#$i = ($_ | Get-Snapshot).count
#$count += $i
#sort $count
"$($_.Name + " = " + $i)"
}

Any help is appreciated. 

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

You don't need to use a hash table but a code block.

Something like this

Get-VM | where { ($_ | Get-Snapshot).count -gt 2 } | 
sort -Descending -Property {($_ | Get-Snapshot).count} | 
foreach {
  #$i = ($_ | Get-Snapshot).count
  #$count += $i
  #sort $count
  "$($_.Name + " = " + $i)"}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
2 Replies
LucD
Leadership
Leadership
Jump to solution

You don't need to use a hash table but a code block.

Something like this

Get-VM | where { ($_ | Get-Snapshot).count -gt 2 } | 
sort -Descending -Property {($_ | Get-Snapshot).count} | 
foreach {
  #$i = ($_ | Get-Snapshot).count
  #$count += $i
  #sort $count
  "$($_.Name + " = " + $i)"}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
DZ1
Hot Shot
Hot Shot
Jump to solution

Thanks LucD, I wish I would have waited just a bit longer to ask, maybe I would have had the answer myself.  I really want to figure out as much as I can before posting, but it's good to know that help is just an ask away.

It worked out just fine, actually, in a past script, I almost had it, I was doing too much, it was easier than I thought.

Get-VM | where { ($_ | Get-Snapshot).count -gt 2 } | 
sort -Descending -Property {($_ | Get-Snapshot).count} | 
foreach {
  $i = ($_ | Get-Snapshot).count
  "$($_.Name + " = " + $i)"}

It works out just fine, thanks again.

0 Kudos