powershell - 用于读取 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
}
}
}
解决方案
从您评论中的信息来看,输入 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
推荐阅读
- python - 使用 OpenCV 编写视频进行视频分类时出错
- haskell - 替换整数或字符列表中的第 n 个元素,或者用户可能新定义的数据类型
- git - 从其他机器上删除以前的 .gitignored 文件的最佳方法是什么?
- python - 根据 SQLAlchemy 中的另一个值从连接中选择多个值
- python - Brython socketio websocket 无法建立连接
- java - Amazon kinesis KCL 1.14.3 - 多个分片和实例问题
- typescript - 如果类型具有特定属性,TypeScript 中是否有一种惯用的方式来要求函数参数?
- facebook - 努力登录我的 Facebook 帐户
- vue-router - Vue路由器在完全匹配时不添加router-link-exact-active类
- wordpress - 自定义 woocommerce 注册表单