如何僅選擇匹配的字串,而沒有貫穿每個“段落”的 if 陳述句?或者我如何一次只從一個輸入物件中選擇一個值?
以下是我的思考程序:
# Here I have treated each rule as a "paragraph" and used a delimiter on "next".
$content = Get-Content C:\firewallrules.txt -Delimiter 'next'
# For every "paragraph"
$content | ForEach-Object {
if($_ -Match 'set ips-sensor'){
"Value Found = " $valuefound
# This prints every match I want to print ONLY the line that matched then iterate through the rest of the document
# Basically, I'm trying to say if($_ -Match 'set ips-sensor') then echo that specific line
$valuefound = $content | Select-String ips-sensor\s .* | % { $_.Matches.Value }
}
else{
"Value Not Found"
}
}
我的預期輸出如下所示:
Value Not Found
Value Found = ips-sensor "default"
Value Found = ips-sensor "default"
Value Not Found
Value Not Found
uj5u.com熱心網友回復:
請嘗試以下操作:
Get-Content C:\firewallrules.txt -Delimiter 'next' |
ForEach-Object {
$match = ($_ | Select-String 'ips-sensor. ').Matches.Value
if ($match) { "Value found: $match" }
else { "Value not found" }
}
或者,更有效地,僅使用一個-match操作,在自動$Matches變數中報告其結果:
Get-Content t.txt -Delimiter 'next' | ForEach-Object {
if ($_ -match 'ips-sensor. ') { "Value found: $($Matches[0])" }
else { "Value not found" }
}
至于你嘗試了什么:
$content | Select-String ...本來應該是$_ | Select-String ...,因為$content是在陣列的所有段落,而不是在手段,所反映的自動$_變數。此外,為了避免匹配兩次沒有必要使用這兩個
-match和一個Select-String電話。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348768.html
標籤:电源外壳
下一篇:獲取傳遞給cli的第一個引數
