powershellregistrywmiget-wmiobject

Write WMI Output to Reg Key always multiline


Hello I try to get this output to a reg key but it only writes the first "$Monitor.ManufacturerName" value if I change the Reg_ADD to Multiline_SZ it would work but it has to be a one line Reg_SZ

I also tried to trim spaces from the decoded values but I also can't get it to work. echo gives the right result and I don't understand why

function Decode {
    If ($args[0] -is [System.Array]) {
        [System.Text.Encoding]::ASCII.GetString($args[0])
    }
    Else {
        "Not Found"
    }
}

$arr=@()
ForEach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {  
   $Manufacturer = Decode $Monitor.ManufacturerName -ne 0 
   $Name = Decode $Monitor.UserFriendlyName -ne 0
   $Serial = Decode $Monitor.SerialNumberID -ne 0
    
    $arr+= "$Manufacturer,$Name, $Serial"
}
[String]$Reg= $arr -replace ("`n","")
echo $Reg
REG ADD <Path to Registry> /v <Name> /t REG_SZ /d $Reg /f 

Thanks

Tried Variables out-string Trim(), replace and so on I assume that the lenght of the strings is the encoded value

It would be nice to have $Manufacturer, $Name, $Serial in one line for each Monitor separated by | example: Display1, Display1,000000000 | Display2, Display2,1111111111 |


Solution

  • Create your $arr array as string array of comma delimited values which I think is easiest by using the -f Format operator.
    Also it is best not use += to add items to an array as it is very memory and time consuming.

    $arr = foreach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {
        $Manufacturer = Decode ($Monitor.ManufacturerName -ne 0)
        $Name         = Decode ($Monitor.UserFriendlyName -ne 0)
        $Serial       = Decode ($Monitor.SerialNumberID -ne 0)
        # output the formatted (comma delimited) string per monitor
        '{0},{1},{2}' -f $Manufacturer, $Name, $Serial
    }
    

    Now combine the elements in the array using the -join operator

    $reg = $arr -join ' | '