我需要一些有关Powershell脚本的帮助,但我不知道该怎么做。
一个非常基本的问题是,如果我有2个配置文件,即1.默认值和2.特定的更新值。如何“比较”两个设置文件,以及如何创建第三个配置文件。
让我们说说,配置一个(default_config.txt):
## general settings ##
user = 1
ringtonetype = 1
ringtonevolume = 10
## user settings
volumespeaker = 10
volumeheadset = 9
## ldap settings
address = 192.168.0.244
subnet = 255.255.255.0
user = admin
password = admin
配置2的具体值(config_new_site.txt):
## general settings ##
ringtonetype = 5
ringtonevolume = 15
## user settings
volumespeaker = 5
volumeheadset = 5
如何创建具有默认值并从“新站点”更新的“ config_new_site_updated.txt”?
它应该像这样:
## general settings ##
user = 1
ringtonetype = 5
ringtonevolume = 15
## user settings
volumespeaker = 5
volumeheadset = 5
## ldap settings
address = 192.168.0.244
subnet = 255.255.255.0
user = admin
password = admin
任何建议都将受到高度赞赏,并在此先感谢您!
答案 0 :(得分:0)
$OldConfig = @(Get-Content "C:\test\default_config.txt")
$NewConfig = @(Get-Content "C:\test\config_new_site.txt")
for ($i = 0; $i -lt $OldConfig.Count; $i++)
{
# Skipping NewLines, Comments/Headlines and Invalid Lines
if($OldConfig[$i] -eq "" -or $OldConfig[$i].Substring(0,1) -eq "#" -or (!$OldConfig[$i] -like "*=*"))
{
continue
}
#Split at '=' and Remove Spaces to get clean Property & Value
$OldProperty = $OldConfig[$i].Split('=')[0].TrimEnd().TrimStart()
$OldValue = $OldConfig[$i].Split('=')[1].TrimEnd().TrimStart()
$NewValue = $null
# Loop throuh new Config and Compare Property
foreach ($NewLine in $NewConfig)
{
# Skipping NewLines, Comments/Headlines and Invalid Lines
if($NewLine -eq "" -or $NewLine.Substring(0,1) -eq "#" -or (!$NewLine -like "*=*"))
{
continue
}
#Split at '=' and Remove Spaces to get clean Property
$NewProperty = $NewLine.Split('=')[0].TrimEnd().TrimStart()
# Compare Property
if($OldProperty -eq $NewProperty)
{
# Set NewVal if Propertys matched
$NewValue = $NewLine.Split('=')[1].TrimEnd().TrimStart()
break
}
}
# Update Property with new Value if Value has changed
if($NewValue -ne $null -and $NewValue -ne $OldValue)
{
$OldConfig[$i] = "$OldProperty = $NewValue"
Write-Host "Set `"$OldProperty`" from `"$OldValue`" to `"$NewValue`""
}
}
$OldConfig | Out-File "C:\test\config_new_site_updated.txt" -Force