说我有一个看起来像这样的配置文件:
{name1}
Settinga=1
settingb=2
settingc=3
{name2}
Settinga=1
settingb=2
settingc=3
{name3}
Settinga=1
settingb=2
settingc=3
我希望能够将{name3}下的设置b = 2行更改为另一个值,例如settingb = 4
它将是Windows操作系统上的文件存储,因此理想情况下,将在PowerShell或批处理命令下完成。
任何人有任何想法或是否有可能?
谢谢
您可以使用Get-Content
读取配置文件,并将节内容存储在嵌套哈希表中的每个名称下,其中名称行是外键,而设置行则分为键和内部值哈希表。我们可以使用Get-Content
将行除以String.Split
,这将使用长度来确定行是名称还是设置。长度1是名称,长度2是设置。
String.Split
这将给出一个哈希表=
,如下所示:
# Read lines from config file
$config = Get-Content -Path .\config.txt
# Use an ordered hashtable to remember order of keys inserted
$sections = [ordered]@{}
# Keep a key which indicates the current name being added
$currentKey = $null
# Go through each line in the config file
foreach ($line in $config) {
# Split each line by '='
$items = $line.Split("=")
# If splitted items is only one value, we found a new name
# Set the new name and create an inner settings dictionary
if ($items.Length -eq 1) {
$currentKey = $line
$sections[$currentKey] = [ordered]@{}
}
# Otherwise we found a normal line
else {
# Only add the setting if the current name is not null
if ($null -ne $currentKey) {
$sections[$currentKey][$items[0]] = $items[1]
}
}
}
然后您可以像这样设置一个(或多个)值:
$sections
然后使用Name Value
---- -----
{name1} {Settinga, settingb, settingc}
{name2} {Settinga, settingb, settingc}
{name3} {Settinga, settingb, settingc}
将更新的哈希表写入新文件:
$sections["{name3}"].settingb = 4
output.txt
Out-File
[显示Out-File
的& {
# Output each outer key first, where the names are stored
foreach ($outerKvp in $sections.GetEnumerator()) {
$outerKvp.Key
# Then output each setting and value
foreach ($innerKvp in $outerKvp.Value.GetEnumerator()) {
"$($innerKvp.Key)=$($innerKvp.Value)"
}
}
# Create new file with the output created in script block
} | Out-File -FilePath .\output.txt
已从{name1}
Settinga=1
settingb=2
settingc=3
{name2}
Settinga=1
settingb=2
settingc=3
{name3}
Settinga=1
settingb=4
settingc=3
的settingb
更新。