我在 arrylist $ProcessToStop 中有一些字串:
> explorer.exe pid: 1844 type: File 20C4: J:\Test
> explorer.exe pid: 1844 type: File 2300: J:\Test
> notepad.exe pid: 3240 type: File 44: J:\Test
> notepad.exe pid: 15272 type: File 44: J:\Test
我想要一個遍歷以上字串的函式,如果它在任何行中找到“notepad.exe”,它應該只將包含“noteapd.exe”的行保存到 $global:arraylist 中并省略所有其他行. 除非有任何包含“notepad.exe”的行,否則它應該將所有行保存到 $global:arraylist 中。
我嘗試了以下方法:
foreach($ToStop in $ProcessToStop){
if($ToStop -like 'notepad.exe'){
$global:arraylist = $ToStop
}
else {
$global:arraylist = $ToStop
}
}
這里的問題是,它將整行保存到 $global:arraylist 中,因為它是 if-else 陳述句。重要的是 $global:arraylist 將用于保存值。但是問題是,我希望如果有notepad.exe,則只應保存那些行。如果不是,則應保存所有行。有任何想法嗎?
uj5u.com熱心網友回復:
您可以使用和方法-match進行過濾。string[].AddRange(..)
值得一提的是,在大多數情況下,$script:作用域變數可以起到與作用域變數相同的$global:作用。
$processToStop = @'
> explorer.exe pid: 1844 type: File 20C4: J:\Test
> explorer.exe pid: 1844 type: File 2300: J:\Test
> notepad.exe pid: 3240 type: File 44: J:\Test
> notepad.exe pid: 15272 type: File 44: J:\Test
'@ -split '\r?\n'
$global:arraylist = [System.Collections.ArrayList]::new()
$processToSearch = [regex]::Escape('notepad.exe')
if($toStop = $processToStop -match $processToSearch)
{
$arraylist.AddRange($toStop)
$arraylist
}
else
{
$arraylist.AddRange($processToStop)
$arraylist
}
uj5u.com熱心網友回復:
我會使用Where-Objectcmdlet 來過濾串列:
$processListOutput = @(
'> explorer.exe pid: 1844 type: File 20C4: J:\Test'
'> explorer.exe pid: 1844 type: File 2300: J:\Test'
'> notepad.exe pid: 3240 type: File 44: J:\Test'
'> notepad.exe pid: 15272 type: File 44: J:\Test'
)
# Use `Where-Object` to find only lines containing "notepad.exe"
$listOfNotepadProcs = @($processListOutput |Where-Object {$_ -like '*notepad.exe*'})
if($listOfNotepadProcs.Count -gt 0){
# At least 1 notepad.exe process line was found, send filtered data
$global:arrayList = $listOfNotepadProcs
}
else {
# No notepad.exe process lines found, send all data
$global:arrayList = $processListOutput
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414555.html
標籤:
上一篇:如何從組中洗掉所有用戶
