简体   繁体   English

PowerShell脚本读取excel并写入文本文件

[英]PowerShell script to read excel and write into text file

I am trying to write a script in power shell to read the first column value in excel, find the value in text file and replace that value with value in second column of the excel file.I am new to the power shell.我正在尝试在 power shell 中编写一个脚本来读取 excel 中的第一列值,在文本文件中找到该值并将该值替换为 excel 文件第二列中的值。我是 power shell 的新手。 Please help.请帮忙。 Below is the code:下面是代码:

$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
        }

    } 
}

Judging by the info from your comment, it looks like the input CSV is a space-delimited file, something like this:从您的评论中的信息来看,输入的 CSV 看起来像是一个以空格分隔的文件,如下所示:

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

Of course, if the delimiter character is something other than a space, change the value for the -Delimiter parameter.当然,如果分隔符不是空格,请更改-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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM