从模板和 excel 自动创建配置
Automate creating configurations from template and excel
我在配置自动化方面遇到了问题。
我有一个配置模板,需要根据 excel 值列表更改所有主机名(标记为 YYY)和 IP(标记为 XXX(仅第 3 个八位字节需要替换))。
现在我有一个包含 100 个不同站点和 IP 的列表,我还想拥有 100 个不同的配置。
一位朋友建议使用以下 Powershell 代码,但它不会创建任何文件..:[=12=]
$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
值替换 left..
您需要保持 模板文本 完整,并从循环内的模板创建一个新副本。然后可以按照您想要的方式更改该副本。每次下一次迭代都将从模板的新副本开始。
无需先将模板文本复制到新位置,然后用新内容覆盖此文件。 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 值列表更改所有主机名(标记为 YYY)和 IP(标记为 XXX(仅第 3 个八位字节需要替换))。 现在我有一个包含 100 个不同站点和 IP 的列表,我还想拥有 100 个不同的配置。
一位朋友建议使用以下 Powershell 代码,但它不会创建任何文件..:[=12=]
$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
值替换 left..
您需要保持 模板文本 完整,并从循环内的模板创建一个新副本。然后可以按照您想要的方式更改该副本。每次下一次迭代都将从模板的新副本开始。
无需先将模板文本复制到新位置,然后用新内容覆盖此文件。 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
}