简体   繁体   English

Powershell 阵列到 csv

[英]Powershell Array to csv

I'm pretty new to powershell and I cant figure out how to get my array into a csv file, where each string goes onto a new row.我对 powershell 很陌生,我不知道如何将我的数组放入 csv 文件中,其中每个字符串都进入一个新行。 Below is some example code.下面是一些示例代码。

$ServerList = "E:\Coding Projects\Powershell\ServerNameList.txt"
$ServerNames = Get-content $ServerList
write-host $ServerNames
$OutputPath = "E:\Coding Projects\Powershell\Output.csv"

$Names = @() 
$Outcome = @()
foreach ($Server in $ServerNames){
    $Names += $Server 
    if ($Server -match "Joe"){
        $Outcome += "pass" 
       
    }else{
        $Outcome += "Fail" 
    }

}
$Names
$Outcome

$csv = New-object psobject -property @{ 
    'User' = $Names -join ',' 
    'Groups' = $Outcome -join ','
    }

write-host $csv

$csv | Select-Object -property User, Groups | Export-csv -path $OutputPath -NoTypeInformation

When I check the csv file, all of the outputs appear on one row instead of iterating down the rowin its specific column.当我检查 csv 文件时,所有输出都出现在一行上,而不是在其特定列中向下迭代行。 Any help would be very useful and appreciated任何帮助都会非常有用和感激

Right now you're creating 2 separate arrays of string values - instead, you'll want to create a single array of objects with two properties:现在,您正在创建 2 个单独的 arrays 字符串值 - 相反,您需要创建一个具有两个属性的对象数组:

$ServerList = "E:\Coding Projects\Powershell\ServerNameList.txt"
$ServerNames = Get-content $ServerList
write-host $ServerNames
$OutputPath = "E:\Coding Projects\Powershell\Output.csv"

$serversWithOutcome = @()
foreach ($Server in $ServerNames){
    $serversWithOutcome += [pscustomobject]@{
        User = $Server 
        Groups = $Server -match "Joe" 
    }
}

$serversWithOutcome | Export-csv -path $OutputPath -NoTypeInformation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM