I'm using VMware PowerCLI to query for datastores that have a certain amount of freespace. The query could come back with nothing, just one, or more than one. I feel like there's got to be an easier way to check if it's one or more than one.
$ds = get-datastore | where {$_.FreeSapceGB -gt 50} | Sort-Object FreeSpaceGB -descending
I know to check if I get results with this
if ($ds)
I know this will check if there's more than one
if ($ds.Count)
If there is more than one, I want to use the one with the most freespace so I use the first one
$ds[0]
But if there is only one, $ds[0] does not work and I have to use just $ds, which makes for too much duplicate coding.
I know I can limit my results with
| Select -first 1
But without limiting the results is there an easier way to do this?
This should do it:
$ds = @(get-datastore | where {$_.FreeSapceGB -gt 50} | Sort-Object FreeSpaceGB -descending)
Then you should always be able to use $ds[0] as long as $ds.Count is greater than 0.