Кажется, я не могу объединить 2 массива, как я хочу, в файл CSV - PullRequest
0 голосов
/ 25 марта 2019

У меня есть два фрагмента кода, которые я хочу объединить в один массив для экспорта в CSV-файл. Цель состоит в том, чтобы я сначала получил информацию с рабочего стола (получение make, model, serial, ...), которую яположить в массив, как это:

$outputArray = @()

foreach($computer in $Desktop){

    $output = [Ordered]@{
        "Merk" = $Desktop.CsManufacturer
        "Model" = $Desktop.CsModel
        "S/n" = $Desktop.BiosSeralNumer
    }
    $outputArray += New-Object PSObject -Property $output

}

Второй момент заключается в том, что я хочу получить всю информацию о мониторе с подключенных мониторов на мое устройство:

$outputArrayMon = @()

    Write-host 
    ForEach ($Monitor in $Monitors)
    {
        $Manufacturer = ($Monitor.ManufacturerName -notmatch 0 | ForEach{[char]$_}) -join ""
        $Name = ($Monitor.UserFriendlyName                     | ForEach{[char]$_}) -join ""
        $Serial = ($Monitor.SerialNumberID         -notmatch 0 | ForEach{[char]$_}) -join ""

        $output = [Ordered]@{
            "Merk /Model" = $Manufacturer
            "Type" = $Name
            "S/n" = $Serial
        }

    $outputArrayMon += New-Object PSObject -Property $output

}

Я пытаюсь объединить ихвот так и экспортируйте его в CSV-файл

$outputArrayRES = $outputArray + $outputArrayMon

$outputArrayRES | Export-Csv -Path $GL\info.csv -NoTypeInformation

Когда я экспортирую в текстовый файл, мои результаты очень нормальные и четкие, но я не могу понять, как заставить его работать в CSV-файле,Вот пример моего вывода в CSV-файл (есть больше выходных данных, но это просто сделать пост немного чище):

csv output

проблема в том, что я даже не получаю некоторые значения в CSV-файле правильно, которые я получаю в текстовом файле.

То, как я хочу, чтобы это работало, заключается в том, что каждое значение должно быть на одной строке вCSV файлвместо 4 отдельных строк я хочу 2 1 = переменные и 2 = значения переменных

EDIT (1):

Странные значения монитора в моем выходном файле

";""
;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;

РЕДАКТИРОВАТЬ (2):

[PSCustomObject]@{
            "Merk" = $Desktop.CsManufacturer
            "Model" = $Desktop.CsModel
            "S/n" = $Desktop.BiosSeralNumer
            "PC Naam" = $Desktop.CsName
            "CPU" = $processor.Name
            "Memory" = "$RAM GB"
            "OS" = $Desktop.WindowsProductName
            "MAC LAN" = $MACLAN
            "MAC WIFI" = $MACWIFI
            "Office" = $officeVersion
            "Merk /Model" = ($Monitor.ManufacturerName -notmatch 0 | ForEach-Object{[char]$_}) -join ""
            "Type" = ($Monitor.UserFriendlyName         -notmatch 0 | ForEach-Object{[char]$_}) -join ""
            "SerialScherm" = ($Monitor.SerialNumberID         -notmatch 0 | ForEach-Object{[char]$_}) -join ""

}

Ответы [ 2 ]

1 голос
/ 26 марта 2019

Вы должны объединить два цикла foreach и создать PSCustomObject s, как bunzab , но со свойствами как для компьютера, так и для его монитора (ов) вместе.

# assuming $Desktop is an array of computer names
$Desktop    = @('pc1','pc2','pc3')
$outputFile = '<PATH AND FILENAME FOR THE OUTPUT CSV FILE>'

$info = foreach($computer in $Desktop) {
    # get the info you want for this computer. You didn't state HOW you did that, probably using Get-ComputerInfo.
    # On my Windows 7 machine this still fails with error:
    # Unable to find an entry point named 'GetFirmwareType' in DLL 'kernel32.dll'
    # so I used these commands instead:

    $pcInfo   = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer
    $biosInfo = Get-WmiObject -Class Win32_Bios -ComputerName $computer

    # store these properties for later use
    $pcName         = $pcInfo.Name
    $pcManufacturer = $pcInfo.Manufacturer
    $pcModel        = $pcInfo.Model
    $pcBiosSN       = $biosInfo.SerialNumber

    # next get the monitor info for this computer
    $Monitors = Get-WmiObject -Class WmiMonitorID -Namespace root\wmi -ComputerName $computer
    foreach($monitor in $Monitors) {
        # emit a PSCustomObject with all properties combined
        [PSCustomObject]@{
            'Computer Naam'       = $pcName
            'Computer Merk'       = $pcManufacturer
            'Computer Model'      = $pcModel
            'BIOS S/N'            = $pcBiosSN
            "Monitor Merk /Model" = ($Monitor.ManufacturerName -ne 0 | ForEach-Object { [char]$_ } ) -join ''
            "Monitor Naam"        = ($Monitor.UserFriendlyName -ne 0 | ForEach-Object { [char]$_ } ) -join ''
            "Monitor S/N"         = ($Monitor.SerialNumberID   -ne 0 | ForEach-Object { [char]$_ } ) -join ''
        }
    }
} 

$info | Export-Csv -Path $outputFile -NoTypeInformation -Delimiter ';'

Надеюсь, это поможет

Примечание: глядя на скриншот, я вижу, что вы дважды щелкнули выходной CSV-файл, чтобы открыть его в Excel, но ваш текущий языковой стандарт (NL) затем помещает все в первый столбец. Вот почему я добавил -Delimiter ';'. Вы также могли бы использовать переключатель -UseCulture, если запускаете его на той же машине, на которой дважды щелкаете выходной CSV-файл.


Редактировать

В своем последнем комментарии вы говорите, что хотите, чтобы информация о мониторе находилась в той же строке, что и информация о компьютере. Это означает добавление дополнительных столбцов к выходному CSV, если на компьютере установлено несколько мониторов. Если это то, что нужно, используйте следующий код:

# assuming $Desktop is an array of computer names
$Desktop    = @('pc1','pc2','pc3')
$outputFile = '<PATH AND FILENAME FOR THE OUTPUT CSV FILE>'

$info = foreach($computer in $Desktop) {
    # get the info you want for this computer. You didn't state HOW you did that, probably using Get-ComputerInfo.
    # On my Windows 7 machine this still fails with error:
    # Unable to find an entry point named 'GetFirmwareType' in DLL 'kernel32.dll'
    # so I used these commands instead:

    $pcInfo   = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer
    $biosInfo = Get-WmiObject -Class Win32_Bios -ComputerName $computer

    # create a PSCustomObject with all properties combined
    # first add computer properties. (insert more when needed)
    $obj = [PSCustomObject]@{
        'Computer Naam'  = $pcInfo.Name
        'Computer Merk'  = $pcInfo.Manufacturer
        'Computer Model' = $pcInfo.Model
        'BIOS S/N'       = $biosInfo.SerialNumber
    }
    # next get the monitor info for this computer
    $Monitors = @(Get-WmiObject -Class WmiMonitorID -Namespace root\wmi -ComputerName $computer)
    for ($i = 0; $i -lt $Monitors.Count; $i++) {
        # add monitor properties to the object
        $obj | Add-Member -MemberType NoteProperty -Name "Monitor $($i + 1) Merk /Model" -Value (($Monitors[$i].ManufacturerName -ne 0 | ForEach-Object { [char]$_ } ) -join '')
        $obj | Add-Member -MemberType NoteProperty -Name "Monitor $($i + 1) Naam"        -Value (($Monitors[$i].UserFriendlyName -ne 0 | ForEach-Object { [char]$_ } ) -join '')
        $obj | Add-Member -MemberType NoteProperty -Name "Monitor $($i + 1) Serienummer" -Value (($Monitors[$i].SerialNumberID   -ne 0 | ForEach-Object { [char]$_ } ) -join '')
    }
    # output the object
    $obj
} 

$info | Export-Csv -Path $outputFile -NoTypeInformation -Delimiter ';' -Force
0 голосов
/ 25 марта 2019

Вместо этого используйте пользовательский объект. Он также даст вам заголовки в вашем CSV, когда вы экспортируете его:

$outputArray = @()

foreach($computer in $Desktop){

    $output = [PSCustomObject]@{
        Merk = $Desktop.CsManufacturer
        Model = $Desktop.CsModel
        S/n = $Desktop.BiosSeralNumer
    }
    $outputArray += New-Object PSObject -Property $output

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...