我需要在 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 行。任何幫助都是極好的
uj5u.com熱心網友回復:
為此,您可以逐行讀取檔案,一旦遇到您要查找的內容的第一個匹配項,請設定一個變數,以備將來匹配相同單詞時使用。
我個人建議您使用switch帶有-File引數的 a 來有效地讀取檔案。有關代碼邏輯的詳細資訊,請參見行內注釋。
$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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478647.html
標籤:电源外壳
