我有一个INI文件:
[Name]
Female = 10
Male = 30
[Class]
Kids = 2
Adult = 10
我想更改每个部分的值。请给我个主意。
我尝试了以下代码:
function Set-OrAddIniValue
{
Param(
[string]$FilePath,
[hashtable]$keyValueList
)
$content = Get-Content $FilePath
$keyValueList.GetEnumerator() | ForEach-Object {
if ($content -match "^$($_.Key)=")
{
$content= $content -replace "^$($_.Key)=(.*)", "$($_.Key)=$($_.Value)"
}
else
{
$content += "$($_.Key)=$($_.Value)"
}
}
$content | Set-Content $FilePath
}
这是代码
答案 0 :(得分:0)
您可以这样做:
$ini = Get-IniContent "<pathToYourIniFile>"
$ini["<yourSection>"]["<yourKey>"] = "<yourValue>"
$ini | out-inifile -FilePath "<pathToYourIniFile>"
答案 1 :(得分:0)
如果将代码更新为以下内容,则会更加成功:
function Set-OrAddIniValue
{
Param(
[string]$FilePath,
[hashtable]$keyValueList
)
$content = Get-Content $FilePath
$keyValueList.GetEnumerator() | ForEach-Object {
if ($content -match "$($_.Key)\s*=")
{
$content= $content -replace "$($_.Key)\s*=(.*)", "$($_.Key)=$($_.Value)"
}
else
{
$content += "$($_.Key)=$($_.Value)"
}
}
$content | Set-Content $FilePath
}
一个问题是,如果您添加额外的键/值对,它们将全部添加到最后一节。换句话说,该代码不支持节。