Reputation: 331
I have a tab delimited text file produced by my backup software. I want to be able to import it as a PowerShell array using Import-CSV.
The problem is that the first 5 lines of the exported file prevent PowerShell from recognizing it as an array:
#List of Media
#Cell Manager: hpdp.domain.local
#Creation Date: 11/08/2018 9:36:09 AM
# Headers
# Medium ID Label Location Status Protection Used [MB] Total [MB] Last Used Last Used_t Pool Type
The way I am able to 'fix' this is by using notepad to delete the first four lines and remove the first # from the header line. The file then looks like this:
Medium ID Label Location Status Protection Used [MB] Total [MB] Last Used Last Used_t Pool Type
id1:id2:id3:id5 [hostname] labelname_31 [Library: 5] Good 13/08/2018 10:01:41 PM 762699.50 762699.50 14/07/2018 10:00:36 PM 1531828836 Tape Drive Pool LTO-Ultrium
I am trying to find a way to get PowerShell to make this change. For example, I try to remove the first four lines as a first step using this line:
(Get-Content $file | Select-Object -Skip 4) | Set-Content $file
The file seems to then lose its tabs so it is no longer delimited.
How can I remove the lines as well as the first # without losing the tabs? Thanks in advance!
Upvotes: 2
Views: 1201
Reputation: 61068
This can be done by something like this
$data = Get-Content $file | Select-Object -Skip 4
$data[0] = $data[0] -replace '^#\s*', ''
now you can overwrite the file if you want to:
$data | Set-Content $file -Force
or use it directly as object in Powershell (a csv object is an array of PSObjects)
$csv = ($data -join [environment]::NewLine) | ConvertFrom-Csv -Delimiter "`t"
or use this converted object to write out the file again
$csv | Export-Csv -Path $file -Delimiter "`t" -NoTypeInformation -Force
Upvotes: 2