1

I need to write a PowerShell script to edit an .ini file. I am not able to use Get-IniContent as it is not available by default. I am using the below function, which works well if there is no duplicate property names in different sections. But the .ini file I am editing does have a property name that is in multiple sections. How would I modify the code to take section into consideration?

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
}


#Set-OrAddIniValue -FilePath $configFile -keyValueList @{"name"=$name}
fhcat
  • 971
  • 2
  • 9
  • 28
  • 3
    If the PsIni module is not available, can you not just cut&paste the code from the module into your project? It's published here https://github.com/lipkau/PsIni/blob/master/PSIni/Functions/Get-IniContent.ps1 (check the license fits your use case), and Out-IniFile is here - https://github.com/lipkau/PsIni/blob/master/PSIni/Functions/Out-IniFile.ps1. Then you can just do what this answer proposes... https://stackoverflow.com/a/22804178/3156906 – mclayton Jun 11 '21 at 21:49
  • 1
    As above, the code for Get-IniContent is tiny, just paste it into your script. – Scepticalist Jun 12 '21 at 08:41
  • Using PInvoke to call native Win32 API functions [GetPrivateProfileString](https://resources.oreilly.com/examples/0636920024132/blob/master/Get-PrivateProfileString.ps1) and WritePrivateProfileString works well for me, with no module dependencies. – leeharvey1 Jun 13 '21 at 13:51

0 Answers0