Weird issue when you use Get-WMIObject AND Get-Service one after the other

I have found a strange issue while gathering information about a Service.

Example1:

$WMSvcstartmode = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='WMSvc'" | select StartMode; $WMSvcstartmode

StartMode

Auto

this returns a value, no problem

Example2:

$WMSvcstatus = Get-Service -Name WMSvc | select Status; $WMSvcstatus

Status

Running

this also returns a value no problem.

However when used together in one script, the first line is what value is returned.

Example3:

$WMSvcstartmode = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='WMSvc'" | select StartMode; $WMSvcstartmode
$WMSvcstatus = Get-Service -Name WMSvc | select Status; $WMSvcstatus

returns this:
StartMode

Auto

and Example4:

$WMSvcstatus = Get-Service -Name WMSvc | select Status; $WMSvcstatus
$WMSvcstartmode = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='WMSvc'" | select StartMode; $WMSvcstartmode

returns only this:
Status

Running

Why is that?

That’s a common gotcha. Keep in mind that Format-Table looks at the first object in the pipeline in order to determine what fields to display, and it generally expects to be piped a list of objects of the same type. When you run your script (and don’t assign the results to a variable), it’s implicitly piped to Out-Default, which decides to use Format-Table because the first object in the pipeline has only one property.

When you run each command by itself, you wind up with two calls to Out-Default / Format-Table, so you see both tables. Where you go from here depends on what you want your function to do. If it is just supposed to display this information at the console, and you aren’t worried about using this in a pipeline or saving the results to a variable, then just pipe each command to Out-Host:

Get-Service -Name WMSvc | select Status | Out-Host
Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='WMSvc'" | select StartMode | Out-Host

Can also pipe to Out-Default as well as Out-Host

Thanks for you reply Dave!

Somtimes the answers smacks you right in the face. This is the solution I needed.

<pre>$WMSvcstatus = Get-Service -Name WMSvc; $WMSvcstatus.status
$WMSvcstartmode = Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='WMSvc'"; $WMSvcstartmode.startmode</pre>