我有一個陣列,需要使用陣列映射檔案內的字串,然后將匹配的字串輸出到檔案。我試過了,但是當我在檔案中找到 2 個匹配字串時,輸出檔案中只有 1 個字串。
$ArrayString = "Network controller TPX","Network controller SXCM", "Adapter controller CNA"
$GetFile = Get-Content .\File
foreach($string in $ArrayString ){
$GetFile | Select-String -Pattern $string | Out-File .\result.txt -Force
}
檔案內的內容如下所示:
Network controller SXCM
Disable
*Enable
Admin Passwordfrom Startup Menu
*Disable
Enable
Adapter controller CNA
Disable
*Enable
Verify on every boot
*Disable
Enable
在某些情況下,$ArrayString 中的字串將匹配 $Getfile 中的 1 并匹配 2 字串。
任何人都可以幫助我。太感謝了
uj5u.com熱心網友回復:
您的代碼的主要問題Out-File
是在回圈內部并且沒有-Append
開關,因此每次回圈迭代都會覆寫檔案。不幸的是,即使沒有匹配,檔案也會由于Out-File
編碼方式而被覆寫,似乎它會在它的塊中打開檔案流,這不應該是這種情況,并且是應該去begin
的眾多原因之一Set-Content
寫入純文本檔案時到 cmdlet。
Out-File
用視覺來解釋這個問題:
# Create a temp file and write some content to it:
$file = New-TemporaryFile
'content' | Set-Content $file.FullName
Get-Content $file.FullName # => content
# `Process` block doesn't run on `AutomationNull.Value`,
# so, the expected would be, if nothing is received from pipeline,
# don't touch the file:
& { } | Set-Content $file.FullName
Get-Content $file.FullName # => 'content' // as expected
# Trying the same with `Out-File`
& { } | Out-File $file.FullName
Get-Content $file.FullName # => null // file was replaced
# dispose the file after testing...
$file | Remove-Item
一些注意事項,Select-String
可以讀取檔案,因此Get-Content
不需要,并且-Pattern
可以采用一組模式來匹配。這是您的代碼的簡化版本。
$ArrayString = "Network controller TPX", "Network controller SXCM", "Adapter controller CNA"
Select-String -Path .\file.txt -Pattern $ArrayString |
ForEach-Object { $_.Matches.Value } | Set-Content result.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/530763.html
標籤:数组电源外壳模式匹配
上一篇:flexbox換行而不是連續列印