Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell: saving strings with a condition

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading