0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That takes care of it for me! Thanks for such a quick response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.