0

我终于得到了我的脚本的功能,现在我想保存到 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 
4

1 回答 1

1

作为“对 PS 有点陌生”的人,我建议您退后几步并简化操作,同时移除-Parallel可能会遮挡输出的开关。正如所评论的,Export-Csvcmdlet [pscustomobject]需要一个项目流,您不能将其与字符串(如"$_;An error occurred.")或具有不同属性的对象结合使用
请参阅:未显示所有属性并将#13906-UnifyProperties 参数添加到 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",
于 2020-12-11T13:14:15.167 回答