Powershell合并来自不同文件的2列,但没有关键字段

时间:2018-12-28 19:38:47

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v6.0

我有2个csv文件,并且具有file1.column1,file1.column2,file2.column1,file2.column2。我想放在下面这样

文件1:

Column1, Column2
1,a
2,b
3,c

文件2:

Column1, Column2
x, abc
y, def
z, ghi

我期望的输出是: File3:

File1.column1, File2.column2
1, abc
2, def
3, ghi

2 个答案:

答案 0 :(得分:2)

其他方法:

#load files
$F1=import-csv "C:\temp\File1.txt"
$F2=import-csv "C:\temp\File2.txt"

#found max element count for 2 files
$Count=[System.Math]::Max($F1.Count, $F2.Count)

#print as you want
0..$Count | select @{N="File1.Column1"; E={$F1[$_].Column1}}, @{N="File2.Column2"; E={$F2[$_].Column2}}

答案 1 :(得分:1)

@PetSerAl是正确的,看来您想将它们合并在行号上,即每行的索引。这是一个带有自定义对象的伪造示例,只需将$ File1和$ File2替换为Import-Csv的输出:

$File1 = @(
[PSCustomObject]@{
    Column1 = 1
    Column2 = "a"
}
[PSCustomObject]@{
    Column1 = 2
    Column2 = "b"
}
[PSCustomObject]@{
    Column1 = 3
    Column2 = "c"
}
)

$File2 = @(
    [PSCustomObject]@{
        Column1 = "x"
        Column2 = "abc"
    }
    [PSCustomObject]@{
        Column1 = "y"
        Column2 = "def"
    }
    [PSCustomObject]@{
        Column1 = "z"
        Column2 = "ghi"
    }
)

for ($i = 0; $i -lt $File1.Count; $i++ )
{
    [PSCustomObject]@{
        "File1.Column1" = $File1[$i].Column1
        "File2.Column2" = $File2[$i].Column2
    }
}