I got some strings in an 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
I want to have a function that goes through the abouve strings and if it finds "notepad.exe" in any line, it should save only the lines that contains "noteapd.exe" into the $global:arraylist and omit all the other lines. unless there any line that contains "notepad.exe" it should save all the lines into $global:arraylist.
i tried with the follwing:
foreach($ToStop in $ProcessToStop){
if($ToStop -like 'notepad.exe'){
$global:arraylist = $ToStop
}
else {
$global:arraylist = $ToStop
}
}
the proble here is, it saves the whole line into $global:arraylist, since it is if-else statement. It is important that $global:arraylist will be used to save the values. BUt the proplem is, i want that if notepad.exe is there, only those lines should be saved. if not, all lines should be saved. Any ideas?
>Solution :
I’d use the Where-Object cmdlet to filter the list:
$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
}