1

This is a two part question about the limits of Out-File and turning string values into objects to use Export-CSV.

I am working on a script to pull various information and add it to an existing csv doc. I am currently using Out-File but I do no think it has the desired functionality.

$date, $computerName, $env:UserName, 'error' | Out-File $report -Append

The above adds all the data in a single column, for instance:

date
computername
username
error

I would like it to read:

date computername username error

I have tried using Export-CSV, but since my variables are strings it just writes the string length instead of the variable. I am happy to use Export-CSV with -Append so long as it reports the items correctly.

Bonus points if we can get the table to have headers like:

date computername username error
8/15/2018 A1 Bob PowerIssue
8/15/2018 A2 Tom InternetIssue

1 Answer 1

4

$date, $computerName, $env:UserName, 'error' is a collection which is getting converted to an array of strings. So then Out-File takes each element of that array and spits it out one element per line.

You could generate a single string. For example,

"$date, $computerName, $env:UserName, error" | Out-File $report -Append

But the better way would be to make an object then export that to csv. Here's an example using [pscustomobject] which requires PS3+

$ExampleObjects = @(
    [pscustomobject]@{
        Date         = Get-Date
        ComputerName = 'A1'
        UserName     = 'Bob'
        Error        = 'PowerIssue'
    },
    [pscustomobject]@{
        Date         = Get-Date
        ComputerName = 'A2'
        UserName     = 'Tom'
        Error        = 'InternetIssue'
    }
)

$ExampleObjects | Export-CSV $report -Append -NoTypeInformation
Sign up to request clarification or add additional context in comments.

1 Comment

This works well. To all other readers, you can input variables in place of the specific items @BenH mentioned above ('A1', 'Bob' etc.). Thanks for the help, this is what I needed.

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.