0

I am trying to get monitor information from workstations. When only one monitor my code works all right. But on multiple monitors it fails.

$connections = get-ciminstance -namespace root/wmi -classname 
WmiMonitorConnectionParams
$videooutput = "$($($connections.VideoOutputTechnology))"

foreach ($output in $videooutput){
if ($output -eq 10) {write-host "DP"}
if ($output -eq 4) {write-host "DVI"}
if ($output -eq 5) {write-host "HDMI"}
if ($output -eq 0) {write-host "VGA"}
else {write-host "unknown"}
}

The issue is the output of the $ videooutput. It returns multiple monitors like this:

4 10

instead of this:

4

10

So in a multiple monitor situation I get "unknown"

S.Raines
  • 17
  • 3

1 Answers1

3

Replace "$($($connections.VideoOutputTechnology))" with $connections.VideoOutputTechnology.

"$($($connections.VideoOutputTechnology))", aside from needlessly using $(...) twice, stringifies the array returned by $connections.VideoOutputTechnology, which by default creates a single string containing the (stringified) elements as a space-separated list.

As an aside, just to clarify: Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. (In PSv5+ Write-Host writes to the information stream, whose output can be captured, but only via 6>; see this answer.)

Also, using a switch statement instead of a foreach loop with multiple if statements enables a simpler solution.

To put it all together:

$connections = get-ciminstance -namespace root/wmi -classname WmiMonitorConnectionParams
$videooutput = $connections.VideoOutputTechnology

switch ($videooutput) {
 10 { "DP"; continue }
 4  { "DVI"; continue }
 5  { "HDMI"; continue}
 0  { "VGA"; continue }
 default { "unknown"}
}
mklement0
  • 382,024
  • 64
  • 607
  • 775