【问题标题】:PowerShell kill multiple processesPowerShell杀死多个进程
【发布时间】:2014-10-22 20:52:52
【问题描述】:

我正在尝试通过 PS 完成以下任务,但在获取所需内容时遇到了问题。我尝试了许多不同的格式来编写这个脚本,这是我认为最接近的。

我运行以下,没有错误,但也没有结果。

$softwarelist = 'chrome|firefox|iexplore|opera'
获取进程 |
Where-Object {$_.ProcessName -eq $softwarelist} |
停止进程-force

这是我正在尝试的另一个示例,但这个示例并未终止我提供的所有进程(W8.1 中的 IE)。

1..50 | % {记事本;计算}

$null = Get-WmiObject win32_process -Filter "name = 'notepad.exe' OR name = 'calc.exe'" |

% { $_.Terminate() }

感谢您的帮助!

【问题讨论】:

    标签: arrays powershell process terminate


    【解决方案1】:

    您的$softwarelist 变量看起来像一个正则表达式,但在您的Where-Object 条件中,您使用的是-eq 运算符。我想你想要-match 运营商:

    $softwarelist = 'chrome|firefox|iexplore|opera'
    get-process |
        Where-Object {$_.ProcessName -match $softwarelist} |
        stop-process -force
    

    您还可以将多个进程传递给Get-Process,例如

    Get-Process -Name 'chrome','firefox','iexplore','opera' | Stop-Process -Force
    

    【讨论】:

    • 我已经尝试过了,这确实适用于 -match 代替 -eq。你被简化的字符串是一种改进,我会用它来代替。 -eq 不能这样和变量数组一起使用吗?
    • 我不确定-eq 对数组的行为如何,但在这种情况下$softwarelist 不是数组,它是一个字符串。要制作一个数组,您必须拆分它,例如$softwarelist -split '|'.
    【解决方案2】:
    # First, create an array of strings.
    $array =  @("chrome","firefox","iexplore","opera")
    
    
    # Next, loop through each item in your array, and stop the process.
    foreach ($process in $array)
    {
        Stop-Process -Name $process
    }
    

    【讨论】:

    • 我喜欢使用多个数组的想法,我觉得数组=灵活性。也许这是我在 DBA 工作时的错误观念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多