Ankh2054
Ankh2054

Reputation: 1153

Replace or add .INI file content

Need to update a .INI file across multiple computers and change the contents. I have the following script that works:

(Get-Content SDA_Apps.ini) | Foreach-Object {
$_ -replace "UserName=.+", "UserName=Test" `
   -replace "UserEmail=.+", "[email protected]" `
   -replace "UserNo=.+", "UserNo=1234" `
   -replace "UserKey=.+", "UserKey=^%&$*$778-" `
   -replace "KEM=.+", "KEM=H10" 
} | Set-Content SDA_Apps.ini

Sometimes those lines of text do not exist and I need to add the text instead of replace it.

This is my attempt to do this - without success:

function setConfig( $file, $key1, $value1, $key2, $value2 ) {
    $content = Get-Content $file
    if ( $content -match "^$key\s*=" ) {
        $content $_ -replace "^$key1\s*=.*", "$key1=$value1" -replace "^$key2\s*=.*", "$key2=$value2"|
        Set-Content $file     
    } else {
        Add-Content $file "$key1 = $value1"
        Add-Content $file "$key2 = $value2"
    }
}

setConfig "SDA_Apps.ini" "UserName" "Test"  "UserEmail" "[email protected]"

Upvotes: 1

Views: 5266

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

I rewrote your function and renamed it to reflect what it actualy does Set-OrAddIniValue:

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
}

The benefit of this function is that you can pass a key-value list as a hashtable to it. It reads the ini file only once, updates the content and saves it back. Here is an usage example:

Set-OrAddIniValue -FilePath "c:\yourinipath.ini"  -keyValueList @{
    UserName = "myName"
    UserEmail = "myEmail"
    UserNewField = "SeemsToWork"
}

Upvotes: 2

Related Questions