Powershell Array to csv

Viewed 143

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. 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. Any help would be very useful and appreciated

1 Answers

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:

$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
Related