1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This is so much simpler than i expected it to be!
Possible improvement: $serversWithOutcome = foreach ... and remove $serversWithOutcome +=. PowerShell automatically creates an array when output of foreach is assigned to a variable like this. Internally PowerShell uses a more efficent method than +=, which recreates the array to accomodate the size for every new item.
@zett42 Absolutely! There's a reason I stuck with OP's use of += here though - "Servers" is the kind of thing we count in 10s, or 100s, maybe 1000s if you're in a big environment - but it's not the kind of thing we count in millions - in other words, it doesn't really matter :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.