Powershell脚本以匹配2个文件之间的字符串并合并

Powershell脚本以匹配2个文件之间的字符串并合并,powershell,Powershell,我有两个包含字符串的文件,两个文件中的每个字符串都由冒号分隔。这两个文件共享一个公共字符串,我希望能够将这两个文件(基于公共字符串)合并到一个新文件中 示例: File1.txt tom:mioihsdihfsdkjhfsdkjf dick:khsdkjfhlkjdhfsdfdklj harry:lkjsdlfkjlksdjfsdlkjs File2.txt mioihsdihfsdkjhfsdkjf:test1 lkjsdlfkjlksdjfsdlkjs:test2 khsdkjfhlkjd

我有两个包含字符串的文件,两个文件中的每个字符串都由冒号分隔。这两个文件共享一个公共字符串,我希望能够将这两个文件(基于公共字符串)合并到一个新文件中

示例:

File1.txt
tom:mioihsdihfsdkjhfsdkjf
dick:khsdkjfhlkjdhfsdfdklj
harry:lkjsdlfkjlksdjfsdlkjs

File2.txt
mioihsdihfsdkjhfsdkjf:test1
lkjsdlfkjlksdjfsdlkjs:test2
khsdkjfhlkjdhfsdfdklj:test3

File3.txt (results should look like this)
tom:mioihsdihfsdkjhfsdkjf:test1
dick:khsdkjfhlkjdhfsdfdklj:test3
harry:lkjsdlfkjlksdjfsdlkjs:test2

你连一个问题都没问。。。你应该展示你迄今为止所做的努力。。。我是说你的密码。
$File1 = @"
tom:mioihsdihfsdkjhfsdkjf
dick:khsdkjfhlkjdhfsdfdklj
harry:lkjsdlfkjlksdjfsdlkjs
"@

$File2 = @"
mioihsdihfsdkjhfsdkjf:test1
lkjsdlfkjlksdjfsdlkjs:test2
khsdkjfhlkjdhfsdfdklj:test3
"@

# You are probably going to want to use Import-Csv here
# I am using ConvertFrom-Csv as I have "inlined" the contents of the files in the variables above
$file1_contents = ConvertFrom-Csv -InputObject $File1  -Delimiter ":" -Header name, code # specifying a header as there isn't one provided
$file2_contents = ConvertFrom-Csv -InputObject $File2  -Delimiter ":" -Header code, test

# There are almost certainly better ways to do this... but this does work so... meh.
$results = @()

# Loop over one file finding the matches in the other file
foreach ($row in $file1_contents) {
    $matched_row = $file2_contents | Where-Object code -eq $row.code

    if ($matched_row) {
        # Create a hashtable with the values you want from source and matched rows
        $result = @{
            name = $row.name
            code = $row.code
            test = $matched_row.test
        }

        # Append the matched up row to the final result set
        $results += New-Object PSObject -Property $result
    }
}

# Convert back to CSV format, with a _specific_ column ordering
# Although you'll probably want to use Export-Csv instead
$results |
    Select-Object name, code, test |
    ConvertTo-Csv -Delimiter ":"