我无法更新 ini 文件。在 Powershell 中将 ini 文件视为哈希表

I cannot update ini file. Treating ini file as hastable in Powershell

我需要更新ini配置文件。我设法将文件转换为 hastable 和更新值。但是当我检查文件中的更改是否正确时,它并没有改变。添加内容不起作用。我需要转换为字符串才能使用 Add-Content 函数吗?

配置文件也用纯文本填充。

"ini" 配置文件:

[sqlScript1Deployment]

sqlServerName                         = '??????????'
olapServerName                        = '??????????'
(...)

我的ps1代码:

[hashtable]$ht = Get-Configuration($iniFilepath)
$ht["sqlScript1Deployment"]["sqlServerName"] = 'Master'

$ht | Add-Content $iniFilepath

"ini" 文件中的预期代码:

[sqlScript1Deployment]
sqlServerName                         = 'Master'

"ini" 文件中的实际结果:

[sqlScript1Deployment]
sqlServerName                         = '??????????'

我不知道你从哪里得到 Get-Configuration 函数,但如果它创建一个哈希表,其中每个键都是 INI 的 Section,每个值都是 name/value像这样配对:

$ht = @{
    'sqlScript1Deployment' = @{
        'sqlServerName'  = '??????????'
        'olapServerName' = '??????????'
    }
}

以下代码可能会有所帮助:

# set the new value for sqlServerName
$ht['sqlScript1Deployment']['sqlServerName'] = 'Master'

# write the Hashtable back to disk as .INI file
$sb = New-Object -TypeName System.Text.StringBuilder

# the Keys are the Sections in the Ini file
# the properties are name/value pairs within these keys
foreach ($section in $ht.Keys) {
    [void]$sb.AppendLine("[$section]")
    foreach ($name in $ht[$section].Keys) {
        $value = $ht[$section][$name]
        # the value needs to be quoted when:
        # - it begins or ends with whitespace characters
        # - it contains single or double quote characters
        # - it contains possible comment characters ('#' or ';')
        if ($value -match '^\s+|[#;"'']|\s+$') {
            # escape quotes inside the value and surround the value with double quote marks
            $value = '"' + ($value -replace '(["''])', '$1') + '"'
        }
        [void]$sb.AppendLine("$name = $value")
    }
}

$sb.ToString() | Out-File $iniFilepath
[void]$sb.Clear()

生成的文件将如下所示:

[sqlScript1Deployment]
sqlServerName = Master
olapServerName = ??????????