excel - 从模板和 Excel 自动创建配置
问题描述
我在配置自动化方面遇到了麻烦。我有一个配置模板,需要根据 excel 值列表更改所有主机名(标记为 YYY)和 IP(标记为 XXX(只有第 3 个八位字节需要替换))。现在我有一个包含 100 个不同站点和 IP 的列表,我还想要 100 个不同的配置。
一位朋友建议使用以下 Powershell 代码,但它没有任何创建文件..:
$replaceValues = Import-Csv -Path "\\ExcelFile.csv"
$file = "\\Template.txt"
$contents = Get-Content -Path $file
foreach ($replaceValue in $replaceValues)
{
$contents = $contents -replace "YYY", $replaceValue.hostname
$contents = $contents -replace "XXX", $replaceValue.site
Copy-Item $file "$($file.$replaceValue.hostname)"
Set-Content -Path "$($file.$replaceValue.hostname)" -Value $contents
echo "$($file.$replaceValue.hostname)"
}
解决方案
您的代码尝试覆盖$contents
循环中的相同字符串,因此如果在您第一次进入循环时替换了值,则不会有任何值YYY
或XXX
值要替换。
您需要保持模板文本完整,并创建循环内模板的新副本。然后可以按照您想要的方式更改该副本。然后,每次下一次迭代都将从模板的新副本开始。
无需先将模板文本复制到新位置,然后用新内容覆盖此文件。Set-Content
如果新文件尚不存在,我们很乐意为您创建一个新文件。
尝试
$replaceValues = Import-Csv -Path 'D:\Test\Values.csv'
$template = Get-Content -Path 'D:\Test\Template.txt'
foreach ($item in $replaceValues) {
$content = $template -replace 'YYY', $item.hostname -replace 'XXX', $item.site
$newFile = Join-Path -Path 'D:\Test' -ChildPath ('{0}.txt' -f $item.hostname)
Write-Host "Creating file '$newFile'"
$content | Set-Content -Path $newFile
}
推荐阅读
- excel - 将具有特定范围的 Excel 文件导入到 datagridview
- python - 使用 pytest 夹具在 s3 中模拟对象
- python - 是否可以在 IDLE 代码中以不同颜色显示定义的变量?
- react-native - 将文件写入目录错误 - Expo FileSystem
- jar - r8 不创建输出 dex 文件
- r - 将单元测试分成更小的部分
- sql - 调整 SQL 以适应由于夏令时而输入数据库的错误日期
- java - Kafka Listener 以什么顺序消费消息?
- vue.js - 如何在 vue.js 模板中使用 annotorious
- statistics - 矩阵的协方差