首页 > 解决方案 > 用于读取 excel 并写入文本文件的 PowerShell 脚本

问题描述

我正在尝试在 power shell 中编写一个脚本来读取 excel 中的第一列值,在文本文件中查找值并将该值替换为 excel 文件第二列中的值。我是 power shell 的新手。请帮忙。下面是代码:

$excel = Import-Csv -Path C:\Users\abc\Desktop\newnbc.csv
foreach ($ex in $excel)
{
    $name = $ex.first  
    $match = Get-Content -Path 'C:\Users\abc\Desktop\all.txt'
    foreach ($ma in $match)
    {
        if ($match | %{$_ -replace $ex.first,$ex.last})
        {
          ((Get-Content -Path C:\Users\abc\Desktop\all.txt -Raw) -replace $name,$ex.last) | Set-Content -Path C:\Users\abc\Desktop\all.txt
        }

    } 
}

标签: powershellcsvreplace

解决方案


从您评论中的信息来看,输入 CSV 似乎是一个以空格分隔的文件,如下所示:

first last
i3-chq-nbc-dt-comcleanup-cmd i3-chq-nbc-dt-d-com-cleanup

当然,如果分隔符不是空格,请更改-Delimiter参数的值。

$fileName = 'C:\Users\abc\Desktop\all.txt'
# get the original content of the text file BEFORE the loop
$content  = Get-Content -Path $fileName -Raw
# then, import the csv with the replacement strings and start replacing the content
Import-Csv -Path 'C:\Users\abc\Desktop\newnbc.csv' -Delimiter ' ' | ForEach-Object {
    $content = $content -replace $_.first, $_.last
}
# finally, save the updated content to file
$content | Set-Content -Path $fileName

推荐阅读