Nick
Nick

Reputation: 1208

Add delimiters to Out-File

No, I cannot use Export-CSV for this. =)

The Question: How can I add custom column delimiters when using Out-File?

The Reason: I essentially have a multithreaded PowerShell script pulling information exporting it to a file. Using Out-File works because it does not lock the file and nothing needs to be in order. However, I need to be able to open this in Excel eventually. My idea is to somehow export the data using Out-File with a special delimiter so that I can open it in excel.

I've been researching for over an hour and every similar question to mine was "solved" with people saying to use Export-CSV which I can not do.

Some things I've tried

foreach($item in $info){
New-Object -TypeName PSCustomObject -Property @{
FolderName = "$($item.Feature1) #"
Owner = "$($item.Feature2) #"
AccessRights = "$($item.Feature3) #"
} | ft -hide | Out-File C:\Test.txt

Using # as the special delimiter, but that leaves a million blank lines.

I've also tried things similar to:

| Select Feature1, Feature2, Feature3 | %{"$($_.Feature1)#", "$($_.Feature2)#", $_.Feature3} | out-file C:\Test.txt -Force -Append 

But that goes through and expands properties that I don't want expanded.

If this is not the best way to go about this, I'm definitely open to helpful and feasible suggestions!

Thanks in advance!

Upvotes: 1

Views: 9813

Answers (2)

Bill_Stewart
Bill_Stewart

Reputation: 24555

One way is to export a csv file for each thread -- Use something unique such as "temp_{0}.csv" -f [Guid]::NewGuid().Guid for the file names to prevent collisions. Once your threads are complete, do something like:

Get-ChildItem temp_*.csv |
  ForEach-Object { Import-Csv $_.FullName } |
  Export-Csv BigOutputFile.csv -NoTypeInformation

Make sure that the Get-ChildItem filename spec doesn't collide with the output filename spec. Then delete temp_*.csv.

Upvotes: 2

Jason Snell
Jason Snell

Reputation: 1465

The solution that jumps to my mind is a little convoluted but would work. Run your code through your foreach loop and create an array of Strings. Add your delimiters inside each string as it goes through the foreach loop and then output the array.

This would let you have the delimiter without using export-csv.

Upvotes: 0

Related Questions