我无法更新ini文件。在Powershell中将ini文件视为hastable

时间:2019-01-03 15:52:16

标签: powershell hashtable

我需要更新ini配置文件。我设法将文件转换为hastable和更新值。但是,当我检查文件中的更改是否正确时,它没有更改。添加内容无效。我需要转换为String才能使用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                         = '??????????'

1 个答案:

答案 0 :(得分:0)

我不知道您从何处获得了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 = ??????????