6

我正在研究修改配置文件的powershell脚本。我有这样的文件:

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

谁应该看起来像这样:

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

如果有键集(Logentrytimeout),只需将其更新为给定值。忽略注释,其中提到了键(以 # 开头的行)。密钥不区分大小写。

如果未设置键(禁用后处理和段启动超时),则将键和值附加到文件中。到目前为止,我的功能是这样的:

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 附加到文件中?
4

6 回答 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将附加到文件中。

于 2013-03-27T16:33:38.027 回答
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"
    }
}
于 2014-04-16T14:37:12.187 回答
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
         }

}

编辑:添加了一个替换铃,和一个不匹配的哨子。

于 2013-03-27T15:44:34.757 回答
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到文件的末尾。我还重命名了该函数以更符合 power shell 命名约定。

于 2013-03-27T15:52:38.893 回答
0

@CarlR 函数适用于 PowerShell 版本 3。这同样适用于PowerShell 版本 2

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

  1. 如果你有这样的一行:

    ; This is a Black line

    你试着做:

    Set-FileConfigurationValue $configFile "Black" 20 -ReplaceExistingValue

    您收到一条关于“更换”的消息,但没有任何反应。

  2. 如果你有这样的两行:

    文件Tmp= 50
    Tmp=50

    你试着做:

    Set-FileConfigurationValue $configFile "Tmp" 20 -ReplaceExistingValue

    你改变了两条线!

    文件Tmp=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
}  
于 2015-04-13T18:23:52.100 回答
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-"
于 2016-10-26T19:44:26.590 回答