powershellhashtable

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


I need to update ini configuration file. I managed to convert the file to hastable and updating values. But when I check if the changes are correct in the file, it hasn't changed. Add-Content doesn't work. do I need to convert to String to use Add-Content function?

Configuration file is filled with plain text also.

"ini" Configuration file:

[sqlScript1Deployment]

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

My ps1 code:

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

$ht | Add-Content $iniFilepath

Expected code in "ini" file:

[sqlScript1Deployment]
sqlServerName                         = 'Master'

Actual result in "ini" file:

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

Solution

  • I have no idea where you got the Get-Configuration function from, but if it creates a hashtable where each Key is a Section for the INI and every Value is a name/value pair like this:

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

    The following code may help:

    # 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()
    

    The resulting file will look like this:

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