Powershell 查找并替换多行字符串

Powershell 查找并替换多行字符串,powershell,Powershell,我试图找到一个字符串并添加程序所需的字符串 我需要代码查看action=runfast是否已经存在,如果已经存在,则什么也不做 $Input = GetContent "${Env:ProgramFiles}\myprogram\file.conf" $replace = @" [MyAction_Log] action = run fast "@ $Input -replace ('action = run fast') -replace ('\[MyAction_Log\]',$rep

我试图找到一个字符串并添加程序所需的字符串

我需要代码查看action=runfast是否已经存在,如果已经存在,则什么也不做

$Input = GetContent "${Env:ProgramFiles}\myprogram\file.conf"

$replace = @"
[MyAction_Log]
action = run fast 
"@

$Input -replace ('action = run fast') -replace ('\[MyAction_Log\]',$replace) | set-content "${Env:ProgramFiles}\myprogram\file.conf"

在肆意更换你认为存在的东西之前,我会检查一下。另外,永远不要使用$Input作为变量名;它是一个自动变量,不会执行您认为它会将其视为只读的操作

$path = "$Env:ProgramFiles\prog\file.conf"
$file = Get-Content -Path $path
$replacementString = @'
[MyAction_Log]
action = run fast
'@

if ($file -notmatch 'action\s=\srun\sfast')
{
    $file -replace '\[MyAction_Log\]', $replacementString |
      Set-Content -Path $path
}

另一种方法可以处理[MyAction_Log]部分中任何位置的操作键


您可以使用-notmatch并跳过需要else和多余的返回。您应该在正则表达式中转义空格。我认为您也意外地将\s更新为替换字符串。仍然应该是一个空格。@BenH再次查找并替换罢工
$Inside = $False
$Modified = $False
$Path = "$( $env:ProgramFiles )\prog\file.conf"

$NewLines = Get-Content $Path | 
    ForEach-Object {

        if( $_.Trim() -like "[*]" ) { $Inside = $False }
        if( $_.Trim() -like "*[MyAction_Log]*" ) { $Inside = $True }

        If( $Inside -and $_ -like "action = *" -and $_ -notlike "*run fast*" ) { $Modified = $True; "action = run fast" } else { $_ }
    }

If( $Modified ) { $NewLines | Set-Content $Path }