在 foreach 对象循环中用 with 填充一个空数组并导出 CSV

populate an empty array from with in a foreach-object loop and export CSV

我终于得到了我的脚本的功能,现在我想保存到 CSV,我正在使用 | Export-CSV -path .\output.csv -Delimiter ";"。但无法获取我需要的数据。

我正在创建一个全局空数组并尝试在 foreach-object 循环中追加项目 但得到一个空的 CSV

我也在运行我的 foraech-object 作为一项工作并通过管道传输 | Export-CSV -path .\output.csv -Delimiter ";" 并获得一组随机数字

如何将我的数据导入 CSV 文件?

我的脚本

Function Get-FileName{
    [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = Get-Location
    $OpenFileDialog.filter = “All files (*.*)| *.*”
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
}

$Importfile = Get-FileName
$Clients = Get-Content $Importfile

$Do = $Clients | ForEach-Object -Parallel {
    # CHECK IF  PC IS IN AD  AND  STATUS  OF  PC IN AD   ENABLED/DISABLED
    $O = get-ADComputer -Identity $_ -Properties Enabled
        if ($O."Enabled" -eq 'TRUE') {

            #CHECK IF PC IS  NETWORK ACCESSIBLE 
            if (Test-Connection -ComputerName $_ -Count 2 -Quiet){

                try{ 
                    #GET  LATEST KB PATCH INSTALLED 
                    Get-HotFix -ComputerName $_ -Description 'Security Update' | Select-Object -Last 1 # tried  to get csv from here  and only capture  what passes through here and not the  catch or elses also tryed appending this to empty array  
                    }
                catch{ 
                    "$_;An error occurred." 
                }  
            }
            else{
                "$_;not on line "
            }
        } 
        else{
            "$_;Disabled PC"
        } 
} -AsJob 

$Do | Receive-Job -Wait   # i tried  " | Export-CSV -path .\output.csv -Delimiter ";" " and  got random  data 

作为“对 PS 有点陌生”的人,我建议您退后几步并简化操作,同时删除 -Parallel 开关这可能会掩盖输出。 正如所评论的那样,Export-Csv cmdlet requires a stream of only [pscustomobject] 项不能与字符串(如 "$_;An error occurred.")或 具有不同属性的对象组合 .
参见: and #13906 Add -UnifyProperties parameter to Select-Object

function UniteProperties { # https://github.com/PowerShell/PowerShell/issues/13906#issuecomment-717480544
  [System.Collections.Generic.List[string]] $propNames = @()
  [System.Collections.Generic.HashSet[string]] $hashSet = @()
  $inputCollected = @($input)
  $inputCollected.ForEach({ 
    foreach ($name in $_.psobject.Properties.Name) {
      if ($hashSet.Add($name)) { $propNames.Add($name) }
    }
  })
  $inputCollected | Select-Object $propNames
}

$Do = 2, 3, 0, 5 | ForEach-Object -Parallel {
    Try {
        [pscustomobject]@{ Name = "Client$_"; HotFix = 1/$_ } # some standard HotFix results
    }
    Catch {
        [pscustomobject]@{ message = "$_;An error occurred." }
    }
}
$Do | UniteProperties | ConvertTo-Csv # Or ... Export-Csv

"Name","HotFix","message"
"Client2","0.5",
"Client3","0.3333333333333333",
,,"Attempted to divide by zero.;An error occurred."
"Client5","0.2",