Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell being too clever

Tags:

powershell

Apologies for what is probably a newbish question.

I am writing some Powershell scripts that run various queries against AD. They will usually return a bunch of results, which are easy to deal with, ie:

$results = myQuery
write-host "Returned " + $results.Count + " results."
foreach ($result in $results) { doSomething }

No worries. However, if there is only 1 result, Powershell automagically translates that result into a single object, rather than an array that contains 1 object. So the above code would break, both at the Count and the foreach. I'm sure the same problem would occur with 0 results.

Could someone suggest an elegant way to handle this? Perhaps some way to cast the results so they are always an array?

like image 740
Neobyte Avatar asked May 27 '09 03:05

Neobyte


1 Answers

Change the first line of code to

$results = @(myQuery)

This will always return an array. See this blog entry for additional details.

like image 116
Robert Harvey Avatar answered Nov 01 '22 09:11

Robert Harvey