首页 > 解决方案 > 从模板和 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)"
     }

标签: excelpowershellnetworkingautomation

解决方案


您的代码尝试覆盖$contents循环中的相同字符串,因此如果在您第一次进入循环时替换了值,则不会有任何值YYYXXX值要替换。
您需要保持模板文本完整,并创建循环内模板的新副本。然后可以按照您想要的方式更改该副本。然后,每次下一次迭代都将从模板的新副本开始。

无需先将模板文本复制到新位置,然后用新内容覆盖此文件。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
}

推荐阅读