Home > database >  Powershell: saving strings with a condition
Powershell: saving strings with a condition

Time:01-18

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?

CodePudding user response:

You can use -match for filtering the string[] and the .AddRange(..) method.

It's worth mentioning that, in most cases, a $script: scoped variable can serve the same purpose as a $global: scoped variable.

$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
}

CodePudding user response:

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
}
  •  Tags:  
  • Related