2

I can get a list of current open windows like this:

Get-Process | where {$_.mainWindowTitle} | format-table mainWindowTitle

How do I write proper syntax to loop and check if Window Name exists and then exit?

Below is the logic I would like to execute:

# BASIC-esque CONDITIONAL LOGIC
# FILENAME: CheckWindowName.ps1

Get-Process | where {$_.mainWindowTitle} | format-table mainWindowTitle

# LOOP START - Loop through $_.mainWindowTitle / mainWindowTitle

If $_.mainWindowTitle CONTAINS "*notepad*" Then
    Exit #break script
Else
    Echo "Hello World! There are no instances of notepad open"
End If

# LOOP END

2 Answers 2

2
Get-Process | where {$_.mainWindowTitle} | ForEach {
    #iterates through processes here. each one can be referenced by $_
}

A basic introduction into how ForEach-Object works can be found on TechNet

Sign up to request clarification or add additional context in comments.

2 Comments

tks, can you expand on the #iterates through processes here. each one can be referenced by $_ logic?
Please research "PowerShell foreach loop" to learn more. For now, just run this: if (ps notepad -ErrorAction SilentlyContinue) {'Notepad is open'}
1

Try to use -like instead of contains. It worked for me.

Below is the example:

PS C:\windows\system32> Get-Process | where {$_.mainWindowTitle -like "notepad" }

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 71 7 1516 6760 95 0.23 6328 notepad 71 7 1516 6676 95 0.11 7212 notepad 68 7 1472 2808 94 8.14 7364 notepad 73 7 1540 1568 95 0.48 8640 notepad 74 8 1820 1672 160 9.41 8884 notepad

1 Comment

use wild card * in front of notepad and after notepad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.