powershellpowershell-core

How to pass array of strings as param from function to get-process/where-object


I'm trying to write a function so I can pass an array of strings as a parameter that is being used by get-process | where-object but It's not matching how I want. The code below kinda shows what I'm having trouble with:

[string[]]$Procs = "notepad","mspaint" 
$Procs -replace '","','|'
$Processes = Get-Process | where-object {$_.name -match $Procs} | select-object name, ID
$Processes2 = Get-Process | where-object {$_.name -match "notepad|mspaint"} | select-object name, ID
write-host "-------- Processes --------"
$Processes
write-host "-------- Processes2 --------"
$Processes2

notepad
mspaint
-------- Processes --------
-------- Processes2 --------

Name         Id
----         --
mspaint   28772
mspaint   32336
notepad    2172
notepad   21168
notepad++ 21056

How do I pass $Procs as as a variable and get output like $Processes2 gives? I tried splitting it and doing a foreach loop but that didn't work either.


Solution

  • $Procs = "notepad","mspaint" is an array already, there is no replacement needed, in fact -replace '","','|' is doing nothing other than enumerating the array, there are no "," in it.

    If you want to use -match because you're looking for a partial match then you should be joining the elements of the array with |:

    [string[]] $Procs = 'notepad', 'mspaint'
    $pattern = $Procs -join '|'
    $Processes = Get-Process | Where-Object Name -Match $pattern | Select-Object name, ID
    

    In case you're looking for an exact match, then -match could be replaced by -in and no joining would be needed:

    [string[]] $Procs = 'notepad', 'mspaint'
    $Processes = Get-Process | Where-Object Name -In $Procs | Select-Object name, ID