We help IT Professionals succeed at work.

using ForEach and Convertto-html

POD-Racer
POD-Racer used Ask the Experts™
on
The script below is supposedly to query the smtp queues for a list of Exchange 2003 servers. The script works if I dont use the convertto-html as the output. If I use convertto-html it only display the result of one server and not the others who have more than 0 queues.

I read from some site that the convertto-html should be outside the ForEach loop so that doesnt overwrite the html for each iteration. What I did below is to move it outside but still Im getting the same one server result. ANy idea?

#list of servers to query from
$server="list.txt"

foreach ($objitem in get-content $server)
{
$query=get-wmiobject -Namespace ROOT\cimv2\applications\exchange -Computername $objitem -Class ExchangeQueue |where {$_.NumberOfMessages -gt 0}
}

$query | convertto-html -property virtualmachine,queuename,numberofmessages > D:result.html
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
You are overwriting the $query variable in the loop, so you are only getting the last result. The most simple approach is not to use a variable:
gc list.txt | % {
  get-wmiobject -Namespace ROOT\cimv2\applications\exchange -Computername $objitem -Class ExchangeQueue | 
    where {$_.NumberOfMessages -gt 0
} | convertto-html -property virtualmachine,queuename,numberofmessages > D:result.html

Open in new window

If you want to maintain your script, use
$query += get-wmiobject -Namespace ROOT\cimv2\applications\exchange -Computername $objitem -Class ExchangeQueue |where {$_.NumberOfMessages -gt 0}

Open in new window

in the loop, and you should be fine.

Author

Commented:
The second solution worked for me after adding $query=@() , i presumed this entry is needed to load it as an array.

By the way on the first option, what is the meaning of %? What does it do in the script?

THanks for the help!
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
Sorry 'bout that. Yes, since we want to have an array, we need to create an empty one first with @().

% is an alias for foreach-object, which is always used in a pipe. Example for getting all running processes starting with a "C":
get-process C* | foreach-object { write-host "running: $($_.ProcessName)" }

Open in new window