[英]PowerShell Import-Csv multiple CSV concatenation of columns
I would like to import multiple .csv files with 3 columns and 100 rows each, to a single .csv with each import going into the next 3 columns (ABC - DEF - GHI) rather than all concatenated into the first 3 columns with 1000s of rows. 我想将多个具有3列和100行的.csv文件导入到单个.csv文件中,每次导入都进入接下来的3列(ABC-DEF-GHI)中,而不是全部并入前1000列的前3列中行。
I have tried Import-Csv
but cannot control where the output is placed. 我尝试了Import-Csv
但无法控制输出的位置。 Will I have to resort to using a COM object ( New-Object -ComObject excel.Application
) or is there a cleaner way to control which cells the import goes into? 我将不得不使用COM对象( New-Object -ComObject excel.Application
)还是有一种更干净的方法来控制导入到哪个单元格?
Header lines are 标题行是
PSComputerName,HotfixID,InstalledOn
But I need to have each loop to write across instead of underneath. 但是我需要让每个循环都可以写,而不是在下面。
PSComputerName,HotfixID,InstalledOn,PSComputerName,HotfixID,InstalledOn,PSComputerName,HotfixID,InstalledOn
What you describe is not a typical use-case for CSVs, and Import-Csv
(or Export-Csv
for that matter) can't handle it at all. 您所描述的不是CSV的典型用例, Import-Csv
(或者说Export-Csv
)根本无法处理。 Both cmdlets convert the rows of a CSV to objects with properties named after the column headers or vice versa. 两个cmdlet都将CSV的行转换为具有以列标题命名的属性的对象,反之亦然。 Hence column headers MUST be unique if you want to use the *-Csv
cmdlets. 因此,如果要使用*-Csv
cmdlet,则列标题必须唯一。
The simplest approach to what you're trying to do would probably be something like this: 您尝试做的最简单的方法可能是这样的:
# read CSV data into distinct variables
$csv1 = Get-Content 'C:\path\to\1.csv'
$csv2 = Get-Content 'C:\path\to\2.csv'
$csv3 = Get-Content 'C:\path\to\3.csv'
# determine maximum number of rows
$max = $csv1.Count, $csv2.Count, $csv3.Count |
Sort-Object
Select-Object -Last 1
# concatenate corresponding rows from each file and write them to the output file
for ($i=0; $i -lt $csv1.Count; $i++) {
# emulate missing rows in case the CSVs don't have the same number of rows
$row1 = if ($csv1[$i]) {$csv1[$i]} else {',,'}
$row2 = if ($csv2[$i]) {$csv2[$i]} else {',,'}
$row3 = if ($csv3[$i]) {$csv3[$i]} else {',,'}
"${row1},${row2},${row3}" | Add-Content 'C:\path\to\output.csv'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.