【问题标题】:PowerShell script to read excel and write into text file用于读取 excel 并写入文本文件的 PowerShell 脚本
【发布时间】:2020-04-23 21:07:51
【问题描述】:

我正在尝试在 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
        }

    } 
}

【问题讨论】:

  • 您面临的问题/错误是什么?在问题中添加这个很好吗?
  • 文件完全替换为第一列中的第一个值
  • 您能否添加一个示例,说明您的 CSV 是什么样的?
  • 第一个最后一个 i3-chq-nbc-dt-comcleanup-cmd i3-chq-nbc-dt-d-com-cleanup
  • Arna k,如果您的 csv 不包含标题,则它不是常见的 csv 文件,因此添加 cvsfile 和 @ 的样本很重要987654324@ 文件(和预期输出)到问题。 (见:How to Ask)。

标签: powershell csv replace


【解决方案1】:

从您评论中的信息来看,输入 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    相关资源
    最近更新 更多