需要在 PowerShell 脚本中查找并替换字符串的一次出现

Need to find and replace one occurrence of a string in a PowerShell script

我需要在 PowerShell 脚本(脚本长约 250 行)中查找并替换一个字符串。脚本中出现了两次字符串“start-sleep -s 10”。我需要编辑并仅将第一次出现更改为“start-sleep -s 30”并保留第二次出现“start-sleep -s 10”。我遇到的问题是我的脚本有几个变体编辑所以我的方法是找到第一次出现的行的范围,进行更改,然后保存脚本并保持其他所有内容不变。PowerShell 的新手所以不确定如何去做。我一直在网上看到文章如何使用 Get-Content 和 Set-Content 查找和替换文件中的文本,但我需要更改第一次出现的“start-sleep -s 10”并保持第二个不变。这就是我所拥有的远:

$ScriptPath = "C:\ScriptsFolder\powershell.ps1"
$scriptcontent = (Get-Content $ScriptPath)
$var1 = "Start-Sleep -s 10"
$var2 = "Start-Sleep -s 30"

$var3 = $scriptcontent | Select-Object -Index (0..250) | Select-String -Pattern $var1 | 
Select-Object -First 1

$var3 -replace $var1 , $var2 | Set-Content $ScriptPath

我得到的不是我想要的,我可以在线进行更改,但是当我设置内容时,它会覆盖整个文件并只保留我编辑的 1 start sleep 行.任何帮助都会很棒

为此,您可以阅读文件 line-by-line,一旦遇到您要查找的第一个匹配项,请设置一个变量,该变量可用于将来匹配同一个词的情况。

我个人建议您使用带有 -File 参数的 switch 来有效地读取文件。有关代码逻辑的详细信息,请参阅内联注释。

$ScriptPath = "C:\ScriptsFolder\powershell.ps1"
$newContent = switch -Wildcard -File $ScriptPath {
    # if this line contains `Start-Sleep -s 10`
    '*Start-Sleep -s 10*' {
        # if we previously matched this
        if($skip) {
            # output this line
            $_
            # and skip below logic
            continue
        }
        # if we didn't match this before (if `$skip` doesn't exist)
        # replace from this line `Start-Sleep -s 10` for `Start-Sleep -s 30`
        $_.Replace('Start-Sleep -s 10', 'Start-Sleep -s 30')
        # and set this variable to `$true` for future matches
        $skip = $true
    }
    # if above condition was not met
    Default {
        # output this line as-is, don't change anything
        $_
    }
}
$newContent | Set-Content $ScriptPath