代碼:
$file= Get-Content "C:\Users\phm4\Desktop\source\status.txt" | select -first 18
$new=$file | select -Skip 12
$nospace=($new)-replace '\s'
$nospace | Out-File new1.txt
import-csv new1.txt -Delimiter "|" | export-csv csvfile.csv
樣本資料:
1|10.9.7.73|-A--|0|505k|505k|2.4T/52.7T(5%)|L3:1.5T
2|10.9.7.74|OK|0|608k|608k|2.4T/52.7T(5%)|L3:1.5T
3|10.9.7.75|OK|0|626k|626k|2.4T/52.7T(5%)|L3:1.5T
4|10.9.7.76|OK|0|0|0|2.4T/52.7T(5%)|L3:1.5T
5|10.9.7.77|OK|0|0|0|2.4T/52.7T(5%)|L3:1.5T
6|10.9.7.78|OK|0|398k|398k|2.4T/52.7T(5%)|L3:1.5T
uj5u.com熱心網友回復:
您不能直接在文本檔案上使用 Import-Csv 的原因是,正確的 CSV 檔案具有必須唯一的標題,而您顯示的示例沒有標題。
這意味著 PowerShell 將使用頂行作為標題,但不能因為有兩列名為“505k”..
你可以做的是:
# get the lines you're interested in and repace whitespaces
$data = Get-Content -Path 'D:\Test\test.txt' -TotalCount 18 | Select-Object -Skip 12 | ForEach-Object { $_ -replace '\s' }
# first find out how many headers you need and create them (as demo, they will be called 'Column_1' etc.)
$n = (($data | ForEach-Object { ($_ -split '\|').Count }) | Measure-Object -Maximum).Maximum
$headers = 1..$n | ForEach-Object { "Column_$_" }
對我來說,如果您想要使用管道符號|作為分隔符的結果 csv 檔案并不清楚,但如果是這種情況,只需將資料寫回包含這些標題的檔案:
# join the created $headers array with the pipe symbol and write to file
($headers -join '|') | Set-Content -Path 'D:\Test\csvfile.csv'
$data | Add-Content -Path 'D:\Test\csvfile.csv'
但是,如果您不想要管道,而是想要一個不同的字符作為分隔符,請使用:
# for demo output a csv with the default comma as delimiter
$data | ConvertFrom-Csv -Header $headers -Delimiter '|' | Export-Csv -Path 'D:\Test\csvfile2.csv' -NoTypeInformation
uj5u.com熱心網友回復:
匯入使用文本檔案匯入,CSV,然后匯出使用它出口的CSV
$path = "C:\Users\phm4\Desktop\source\status.txt"
$csv = "C:\Users\phm4\Desktop\source\csvfile.csv"
$import = import-csv $path -Delimiter "|"
$import | export-csv $csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/376430.html
