Powershell函数用于替换或添加文本文件中的行

6

我是一名帮助翻译的助手。以下是您需要翻译的内容,涉及IT技术。您需要修改配置文件的powershell脚本,其中文件的格式如下:

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

应该长成这样:

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

如果存在关键字(Logentrytimeout),只需将其更新为给定的值。忽略包含该关键字的注释(以#开头的行)。关键字不区分大小写。

如果未设置关键字(disablepostprocessing和segmentstarttimeout),请将关键字和值追加到文件中。目前我的函数如下:

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"
  • 什么是正确的正则表达式?
  • 如何检查是否进行了替换?
  • 如果没有进行替换:那么我该如何将$key+" = "+$value附加到文件中呢?
6个回答

14

假设您想要替换的$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 将被追加到文件中。


3

以下是具有一些参数化和必要时提供详细输出的上述函数的更新版本。

   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"
    }
}

问题是,如果一个键/值存在但被注释掉了,我该如何取消注释或抛出异常?我正在使用这个独立程序,但我该如何将其用作实际的函数,并将参数作为字符串传递,以便我可以使用..("./foo.cfg", "foo", "bar, baz")。 - Jon Weinraub

2
我会这样做:

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
         }

}

编辑:添加了替代铃声和不匹配哨声。


1
将该函数更改为以下内容:
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添加到文件末尾。我还将函数重命名以更符合PowerShell命名约定。


0

@CarlR 函数是为 PowerShell 版本 3 设计的。这里将它适配至 PowerShell 版本 2

编辑:更改正则表达式以修复 Set-FileConfigurationValue 的两个错误:

  1. 如果您有一行像这样的文本:

    ; This is a Black line

    并尝试执行以下操作:

    Set-FileConfigurationValue $configFile "Black" 20 -ReplaceExistingValue

    您会收到有关“替换”的消息,但不会发生任何事情。

  2. 如果您有两行像下面这样的文本:

    filesTmp=50
    Tmp=50

    并尝试执行以下操作:

    Set-FileConfigurationValue $configFile "Tmp" 20 -ReplaceExistingValue

    您会发现这两行都被更改了!

    filesTmp=20 Tmp=20

这是最终版本:

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"
    }
}

我还添加了一个从配置文件读取的函数。

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
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
    }
}

使用方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接