如何使用PowerShell导入文件,并用脚本中定义的占位符变量替换所有现有占位符变量?
我有许多.txt文件用作Arista交换机部署的标准化模板,但我想使用PowerShell快速更新它们。 我用$variables替换了这些模板中所有必需的值,现在我正试图编写一个脚本来替换它们 我找到了一个我喜欢的解决方案,但它对我不起作用。我不确定我在这里做错了什么。 这是源文件中的一个片段:如何使用PowerShell导入文件,并用脚本中定义的占位符变量替换所有现有占位符变量?,powershell,templates,replace,Powershell,Templates,Replace,我有许多.txt文件用作Arista交换机部署的标准化模板,但我想使用PowerShell快速更新它们。 我用$variables替换了这些模板中所有必需的值,现在我正试图编写一个脚本来替换它们 我找到了一个我喜欢的解决方案,但它对我不起作用。我不确定我在这里做错了什么。 这是源文件中的一个片段: router bgp $asn router-id 10.1.1.1 bgp listen range 192.168.$id.0/25 peer-group cluster$id re
router bgp $asn
router-id 10.1.1.1
bgp listen range 192.168.$id.0/25 peer-group cluster$id remote-as $asn
neighbor cluster$id peer-group
neighbor cluster$id update-source Loopback0
neighbor cluster$id description cluster$id-BGP
neighbor cluster$id ebgp-multihop 3
neighbor cluster$id maximum-routes 12000
network 10.1.1.1/32
exit
以下是powershell脚本的一个片段:
$newvars = @{
'$id' = '101'
'$asn' = '12345'
}
$template = '.\Arista\arista.txt'
$destination_file = '.\switchconfig' + $id + '.txt'
Get-Content -Path $template | ForEach-Object {
$line = $_
$newvars.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $destination_file
我想要的是定义一组变量(最多30个),然后用脚本中包含的值替换文本文件中该变量的每个实例。
此解决方案看起来不错,因为它可以避免反复执行“替换”,但它只是按原样打印文件。由于powershell使用$作为变量的标识符(保留),因此在运行方法时必须正确转义它。下面是一个小小康,但做什么,你正在寻找。在您的
$
签名之前,使用\
更新您的词典,以替换包含$
的文本
$newvars = @{
'\$id' = '101'
'\$asn' = '12345'
}
$template = "C:\temp\new.txt"
$destination_file = "C:\temp\replaced.txt"
$data = @()
foreach($line in Get-Content $template) {
foreach($key in $newvars.Keys) {
if ($line -match $key) {
$line = $line -replace $key, $newvars[$key]
}
}
$data += $line
}
$data | Out-File $destination_file
还有一件事要注意。。在文件中,您将$id定义为文件名。我不确定在哪里,但该变量将始终为null,因为它尚未定义(除非此处的代码片段与实际代码不同)
如果要使用Invoke表达式,可以按以下方式使用它:
$id = '101'
$asn = '12345'
$template = (Get-Content "C:\temp\new.txt") | out-string
$data = Invoke-Expression "`"$template`""
$data | Out-File "C:\Temp\test.txt"
您必须确保您的变量($id,$asn)在计算文本文件中的变量时,有一个值要替换。我现在看到$id有错误,谢谢。最初,我在顶部有一个定义的变量列表。另一个用户评论说此解决方案可能有效,我可以跳过所有的“foreach”内容。您认为如何?请参阅更新@n0ttsweetThanks以了解update!如果我能再给你一次投票,我会的!不过我认为更新中有一个错误?
$data=Invoke Expression“`$template`
我在带有“”的部分出错。应该是“”我是个白痴。我读了“作为一个”。我忘了它是Powershell的逃逸角色。它工作得很好。我很高兴你找到了它