Scott
Scott

Reputation: 13

powershell Export to csv from a ForEach

Pardon me but I an not strong in PowerShell (version 5) as I want to be. I have played with a lof of solutions found on this site but haven't stumbled on a solution for this code. Basically this code works and provides the results I need (viewing by write-host) but I need to get this to putput to a CSV file with a header line.

Any help would be appreciated (already spent more days on this than I care to admit...)

My code as it stands:

# Input File to test from
$csvFile = 'c:\temp\20181013.csv' 
# Read the file   
$computers =import-csv $csvFile
# Process the file
ForEach ($computer in $computers) 
{
$Workstation_Name = $($Computer.Workstation_Name)   #Read the workstation name from the file
$Logon_Duration = $($Computer.Logon_Duration)       #Read the logon duration from the file
$cmp = get-adcomputer -identity $Workstation_Name -Properties Location  #Query Active Directory and get the location field
$Start = $cmp.Location.IndexOf(" ") #Extract the building number from the location field which is between the Bldg:  and ; 
$End = $cmp.Location.IndexOf(";")
$Bldg = $cmp.location.Substring($Start, $End - $Start)  #Extract just the building number
Write-Host $Workstation_Name, $Bldg, $Logon_Duration        #Write the Workstation name, Building number and logon duration
} 

Results look like:

System1  12345 82
Sales1  12345 190
Sales2  123 40
System2  23456 136
…

Need it to look like (in csv file)

Workstation_Name, Bldg, Duration
System1, 12345, 82
Sales1, 12345, 190
Sales2, 123, 40
System2, 23456, 136
…

Upvotes: 1

Views: 1401

Answers (2)

JPBlanc
JPBlanc

Reputation: 72630

You can try to replace :

Write-Host $Workstation_Name, $Bldg, $Logon_Duration

by

$obj = [PSCustomObject]@{"Workstation_Name"= $Workstation_Name; "Bldg"=$Bldg; "Duration"=$Logon_Duration}
$obj | export-csv -Path " 'c:\temp\final.csv' -Append

Upvotes: 1

malita
malita

Reputation: 61

declare an empty object before the foreach, then fill it in the loop like this:

$outputObject = @()

ForEach ($computer in $computers) {

    $itemline = "" | select "Workstation_Name", "Bldg", "Duration"
    $itemline.Workstation_Name = $($Computer.Workstation_Name)
    $itemline.Duration = $($Computer.Logon_Duration)
    $itemline.Bldg = ...

    $outputObject += $itemline 
} 
$outputObject | Export-Csv -Path C:\temp\example.csv -NoTypeInformation

Upvotes: 1

Related Questions