Can't use Array with Where-Object on Get-Process

Tom Weustink 21 Reputation points
2022-05-02T13:14:55.573+00:00

I am writing a script where, amongst other things, it needs to react on process used by a popup window.
This popup window has the name in the MainWindowTitle property of Get-Process.

As a test I create the following array:

$WindowTitleNames = @("notepad","powershell")

I then open Notepad.

When I run the following, without using the array, I get this output:

Get-Process | Where-Object MainWindowTitle -Match "notepad" | select Processname, MainWindowTitle

ProcessName MainWindowTitle


Notepad Untitled - Notepad
notepad++ *new 4 - Notepad++

But when I run it with the array it doesn't return anything.
However, when I add "Untitled - Notepad" to the array, it will show the Notepad process.

Get-Process | Where-Object {$_.MainWindowTitle -in $WindowTitleNames} | select Processname, MainWindowTitle

ProcessName MainWindowTitle


Notepad Untitled - Notepad

Changing the -in to -match or -like doesn't help here.
It seems that when I want to use an array I have to use exact MainWindowTitle values.
But my problem is that I don't always know which name will popup, so I want to use "notepad", or "powershell" (these are examples).
Then I can create a if statement like this:

if ($WindowTitle.ProcessName -eq 'notepad' -or 'powershell') {
    this-function
    that-function
}

I hope someone can explain why I can't use a array here, and what I can do to make it work like I have in mind.
Of course I have searched and I can find examples, but not in relation to Get-Process and $_.MainWindowTitle or something similar.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,448 questions
{count} votes

Accepted answer
  1. Rich Matheisen 45,671 Reputation points
    2022-05-02T14:46:06.483+00:00

    You can't use "-match" because that operates on a string object. You can't use "-in" because that uses exact matches, not partial ones.

    $WindowTitleNames = @("notepad", "powershell")   # values may be simple strings or regexes
    Get-Process "notepad" | 
        ForEach-Object {
            foreach ($title in $WindowTitleNames) {
                if ($_.MainWindowTitle -match $title) {
                    Select-Object -InputObject $_ Processname, MainWindowTitle
                }
            }
        }
    

0 additional answers

Sort by: Most helpful