1

Using Add-Content to input multiple variables to a csv file will write each variable to the csv in a new row, such as the following:

Code

$name, $dateTime, $task | Add-Content $csv  -Force

Results

$name
$dateTime
$task

I would like to loop the above code with new variable values each time but would prefer the variables to input to new columns for results such as the following:

$name $dateTime $task
$name $dateTime $task
$name $dateTime $task

How can I modify my code to input each of the 3 variables into a new column, then on the next pass, input the 3 new values on the next row across columns 1,2 and 3 like the above example?

Thanks

7
  • 1
    Where are the values coming from? How are you assigning the variables $name etc? Commented Nov 26, 2018 at 17:25
  • 4
    Add-Content works with strings, "$name, $dateTime, $task" | Add-Content to make your variables into a string line of the right kind for your CSV. Commented Nov 26, 2018 at 17:32
  • 2
    (Or use Export-Csv -Append but you'll need to make a PSCustomObject of the right shape, which will only work if the CSV format is exactly what PowerShell wants) Commented Nov 26, 2018 at 17:33
  • 4
    this sounds like an XY problem. You are trying to make a CSV? If you have proper objects you could just look into Export-CSV. For now you could just "$name $dateTime $task" | Add-Content $csv -Force Commented Nov 26, 2018 at 17:34
  • @Matt Thanks, that does write it across but only in a single cell. I would like each of the 3 variables to log into A1, B1, C1. Commented Nov 26, 2018 at 18:46

1 Answer 1

3

Using a suggestion from @TessellatingHeckler, I used Export-CSV -Append and created a pscustomobject like so:

$logData = @(
 [pscustomobject]@{
  Name = $name
   DateTime = $dateTime
    Task = $task
}
)
$logData | Export-Csv $csv -Append -NoTypeInformation

By doing so I achieved two desirable effects; column headers and each variable is written to it's own cell per each iteration of the loop.

Results

Name  DateTime  Task
$name $dateTime $task
$name $dateTime $task

Thanks, everyone.

Sign up to request clarification or add additional context in comments.

Comments

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.