Home > Enterprise >  POWERSHELL - Writing parameters to ini file from array, with new line on every parameter
POWERSHELL - Writing parameters to ini file from array, with new line on every parameter

Time:09-12

Im trying to write a script in powershell that will add new parameters from updates into a ini file.

They are categorized with [categorie]

It checks what parameters are missing and then i want them to be added under the categorie.

 $inipath = "somepath"
  $list =@([PSCustomObject] @{ type = "\[cat\]"; values = "par1=N","par2=N", "par3=N"})

foreach($entry in $list){
    if(Select-String -Path $inipath -Pattern $entry.values -SimpleMatch -Quiet){
    }
    else{
        $parameter  = @([PSCustomObject] @{ type = $entry.type; values =` $entry.values })
   }
}

$tlength = $parameter.type.length
    for($x=0; $x -le $tlength; $x   ){
        $vlength = $parameter[$x].values.Length
        for($y=0;$y -le $vlength; $y  ){
            $par = $parameter[$x].values[$y]
            $par = $par -join '`n'
    $fileContent = Get-Content $inipath
    $linenumber= Get-Content $inipath | select-string $parameter[$x].type
    $fileContent[$lineNumber.LineNumber  1]  = $par
    $fileContent | Set-Content $inipath  
    
    }

Right now it recognizes the missing parameters and prints them but its printing them like this:

[cat]par1=Npar2=N=par3=N

Desired out put would be

[cat]
par1=N
par2=N
par3=N

CodePudding user response:

In PowerShell, strings wrapped in single quotes are taken literally, while strings wrapped in double quotes are interpreted and processed for variables, etc.

You need to change:

$par = $par -join '`n'

to:

$par = $par -join "`n"

CodePudding user response:

In the end i fixed it by replacing the function with a function that replaces the entire [category] with [category] "`n" $param

    $tlength = $parameter.type.length
    for($x=0; $x -le $tlength; $x   ){
        $vlength = $parameter[$x].values.Length
        for($y=0;$y -le $vlength; $y  ){
            if(!$vlength){
                echo "no parameters"
            }
            elseif(!$parameter[$x].values[$y]){
                echo "no parameters"
            }
            else{
            $par = $parameter.type[$x]
            $a = $parameter.type[$x]   "`n"   $parameter[$x].values[$y]
            $a = $a -replace '\\',''
            echo $a
    (Get-Content $inipath) -replace $par, $a | Set-Content $inipath  
            }
    }
}

now it prints

[cat]
param1=n
param2=n
  • Related