【问题标题】:How to exit powershell script if window name exists?如果窗口名称存在,如何退出 powershell 脚本?
【发布时间】:2015-03-25 01:00:23
【问题描述】:

我可以像这样获取当前打开的窗口列表:

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

如何编写正确的语法来循环并检查窗口名称是否存在然后退出?

下面是我要执行的逻辑:

# 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

【问题讨论】:

    标签: powershell foreach powershell-4.0


    【解决方案1】:
    Get-Process | where {$_.mainWindowTitle} | ForEach {
        #iterates through processes here. each one can be referenced by $_
    }
    

    ForEach-Object 工作原理的基本介绍可以在TechNet 上找到

    【讨论】:

    • tks,你能扩展#iterates through processes here. each one can be referenced by $_的逻辑吗?
    • 请研究“PowerShell foreach 循环”以了解更多信息。现在,只需运行以下命令: if (ps notepad -ErrorAction SilentlyContinue) {'Notepad is open'}
    【解决方案2】:

    尝试使用 -like 代替 contains。它对我有用。

    下面是例子:

    PS C:\windows\system32> 获取进程 |其中 {$_.mainWindowTitle -like "notepad" }

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

    【讨论】:

    • 在记事本前面和记事本后面使用通配符 *。
    猜你喜欢
    • 2016-06-23
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2021-11-15
    相关资源
    最近更新 更多