Powershell function to replace or add lines to text files

I am working on a powershell script file that modifies configuration files. I have these files:

#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 1800

which should look like this:

#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 180
disablepostprocessing = 1
segmentstarttimeout = 180

If there is a set of keys (Logentrytimeout), just update it to the specified value. Ignore comments that mention the key (lines starting with C #). The key is case insensitive.

If the key is not set (disablepostprocessing and segmentstarttimeout), add the key and value to the file. My function so far looks like this:

function setConfig( $file, $key, $value )
{
  (Get-Content $file) |
  Foreach-Object {$_ -replace "^"+$key+".=.+$", $key + " = " + $value } |
  Set-Content $file
}

setConfig divider.conf "Logentrytimeout" "180"
setConfig divider.conf "disablepostprocessing" "1"
setConfig divider.conf "segmentstarttimeout" "180"
  • What is the correct regular expression?
  • How to check if there was a replacement?
  • If there was no replacement: how can I add a value to the file $ key + "=" + $?
+5
source share
6

, $key, ,

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

setConfig "divider.conf" "Logentrytimeout" "180" 

​​ $key = $value.

+13

, .

   Function Set-FileConfigurationValue()
{
    [CmdletBinding(PositionalBinding=$false)]   
    param(
        [Parameter(Mandatory)][string][ValidateScript({Test-Path $_})] $Path,
        [Parameter(Mandatory)][string][ValidateNotNullOrEmpty()] $Key,
        [Parameter(Mandatory)][string][ValidateNotNullOrEmpty()] $Value,
        [Switch] $ReplaceExistingValue,
        [Switch] $ReplaceOnly
    )

    $content = Get-Content -Path $Path
    $regreplace = $("(?<=$Key).*?=.*")
    $regValue = $("=" + $Value)
    if (([regex]::Match((Get-Content $Path),$regreplace)).success)
    {
        If ($ReplaceExistingValue)
        {
            Write-Verbose "Replacing configuration Key ""$Key"" in configuration file ""$Path"" with Value ""$Value"""
            (Get-Content -Path $Path) | Foreach-Object { [regex]::Replace($_,$regreplace,$regvalue) } | Set-Content $Path
        }
        else
        {
            Write-Warning "Key ""$Key"" found in configuration file ""$Path"". To replace this Value specify parameter ""ReplaceExistingValue"""
        }
    } 
    elseif (-not $ReplaceOnly) 
    {    
        Write-Verbose "Adding configuration Key ""$Key"" to configuration file ""$Path"" using Value ""$Value"""
        Add-Content -Path $Path -Value $("`n" + $Key + "=" + $Value)       
    }
    else
    {
        Write-Warning "Key ""$Key"" not found in configuration file ""$Path"" and parameter ""ReplaceOnly"" has been specified therefore no work done"
    }
}
+3

:

function setConfig( $file, $key, $value )
{
  $regex = '^' + [regex]::escape($key) + '\s*=.+'
  $replace = "$key = $value"
  $old = get-content $file
  $new = $old -replace $regex,$replace 

  if (compare-object $old $new)
    {  
      Write-Host (compare-object $old $new |  ft -auto | out-string) -ForegroundColor Yellow
      $new | set-content $file
    }

    else {
           $replace | add-content $file
           Write-Host "$replace added to $file" -ForegroundColor Cyan
         }

}

: , .

+2

:

function Set-Config( $file, $key, $value )
{
    $regreplace = $("(?<=$key).*?=.*")
    $regvalue = $(" = " + $value)
    if (([regex]::Match((Get-Content $file),$regreplace)).success) {
        (Get-Content $file) `
            |Foreach-Object { [regex]::Replace($_,$regreplace,$regvalue)
         } | Set-Content $file
    } else {
        Add-Content -Path $file -Value $("`n" + $key + " = " + $value)          
    }
}

, , :

Set-Config -file "divider.conf" -key "Logentrytimeout" -value "180"

: , . $key, , $value. , $key = $value . , .

+1

@CarlR PowerShell 3. , PowerShell 2.

EDIT: Set-FileConfigurationValue:

  • :

    ; This is a Black line

    :

    Set-FileConfigurationValue $configFile "Black" 20 -ReplaceExistingValue

    "", .

  • :

    filesTmp = 50
    Tmp = 50

    :

    Set-FileConfigurationValue $configFile "Tmp" 20 -ReplaceExistingValue

    !

    filesTmp = 20 Tmp = 20

This is the final version:

Function Set-FileConfigurationValue()
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True)]
        [ValidateScript({Test-Path $_})]
        [string] $Path,
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string] $Key,
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()] 
        [string]$Value,
        [Switch] $ReplaceExistingValue,
        [Switch] $ReplaceOnly
    )

    $regmatch= $("^($Key\s*=\s*)(.*)")
    $regreplace=$('${1}'+$Value)

    if ((Get-Content $Path) -match $regmatch)
    {
        If ($ReplaceExistingValue)
        {
            Write-Verbose "Replacing configuration Key ""$Key"" in configuration file ""$Path"" with Value ""$Value"""
            (Get-Content -Path $Path) | ForEach-Object { $_ -replace $regmatch,$regreplace } | Set-Content $Path
        }
        else
        {
            Write-Warning "Key ""$Key"" found in configuration file ""$Path"". To replace this Value specify parameter ""ReplaceExistingValue"""
        }
    } 
    elseif (-not $ReplaceOnly) 
    {    
        Write-Verbose "Adding configuration Key ""$Key"" to configuration file ""$Path"" using Value ""$Value"""
        Add-Content -Path $Path -Value $("`n" + $Key + "=" + $Value)       
    }
    else
    {
        Write-Warning "Key ""$Key"" not found in configuration file ""$Path"" and parameter ""ReplaceOnly"" has been specified therefore no work done"
    }
}

I also added a function to read from the configuration file

Function Get-FileConfigurationValue()
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True)]
        [ValidateScript({Test-Path $_})]
        [string] $Path,
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [string] $Key,
        [Parameter(Mandatory=$False)]
        [ValidateNotNullOrEmpty()] 
        [string]$Default=""
    )

    # Don't have spaces before key. 
    # To allow spaces, use "$Key\s*=\s*(.*)"
    $regKey = $("^$Key\s*=\s*(.*)")

    # Get only last time 
    $Value = Get-Content -Path $Path | Where {$_ -match $regKey} | Select-Object -last 1 | ForEach-Object { $matches[1] }
    if(!$Value) { $Value=$Default }

    Return $Value
}  
0
source
function sed($filespec, $search, $replace)
{
    foreach ($file in gci -Recurse $filespec | ? { Select-String $search $_ -Quiet } )
    { 
    (gc $file) | 
     ForEach-Object {$_ -replace $search, $replace } | 
     Set-Content $file
    }
}

Using:

sed ".\*.config" "intranet-" "intranetsvcs-"
0
source

All Articles