Clicky

20221030

modifyINI.ps1: an INI file modification script

The next script modifies one value in one section in an INI file. The INI filename stays the same. No input validation, no backup, no fancy command line parsing, no help, no nothing...

The  regexp's are stolen from: https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/

<#

    Script: modifyINI.ps1
    Purpose: Change values in INI files
    Date: 20-Oct-2022
    Version: 0.1
 
    Usage: 
 
PS C:\> modifyINI.ps1 "INI file" "[Section]" "Key" "New value" 
   
    --- c:\temp\test.ini -------------------
    [System]
    Colors=256
    memSize=20MB
    cpuCores=4
    ----------------------------------------
       
    PS C:\> modifyINI.ps1 "c:\temp\test.ini" "[System]" "memSize" "35MB"

    --- c:\temp\test.ini -------------------
    [System]
    Colors=256
    memSize=35MB
    cpuCores=4
    ----------------------------------------

#>

    if ($args.count -NE 4) {Exit}
   
    $iniFile    = $args[0]
    $srcSection = $args[1]
    $srcKey     = $args[2]
    $newVal     = $args[3]
 
    $tabChr     = ""        #--- Ident for val/var lines
    $spaceChr   = ""        #--- Space before/after "=", for readability.
    $section    = $NULL
   
    $srcFile = get-content $iniFile
    $tmpFile = New-TemporaryFile


    foreach ($line in $srcFile) {
       
        $bareLine = $line.trim()
       
        if ($bareLine -MATCH "^\[(.+)\]") {             #--- [Section]...
         
            $section = $bareLine
           
        } ELSEIF ($bareLine -MATCH  "(.+?)\s*=(.*)") {  #--- key=val...
         
            $key = $bareLine.split("=")[0].trim()
            $val = $bareLine.split("=")[1].trim()
       
            if (($srcSection -EQ $section) -AND ($srcKey -EQ $key)) {
               
                $bareLine = "$tabChr$key$spaceChr=$spaceChr$newVal"
               
            } ELSE {
               
                $bareLine = "$tabChr$key$spaceChr=$spaceChr$val"
               
            }
       
        } #--- ELSE do nothing $bareLine...
       

        write-output "$bareLine" | out-file $tmpFile -append
       
    }    
   
    copy-item $tmpFile $iniFile -force
    remove-item $tmpFile -force

   

Real Time Web Analytics