首页 > 解决方案 > 用于查找用户运行的进程的 powershell 脚本,如果没有发送电子邮件

问题描述

在 PowerShell 中非常新。我必须写一个脚本

  1. 将首先根据命名方案找出 VM,然后

  2. 查询每个 VM 以查找是否有任何 PowerShell 进程在特定用户下运行,例如“userA”,如果在任何 VM 上找不到该进程,则

  3. 它将编译一个没有运行进程的虚拟机列表,然后通过电子邮件发送。

我已经弄清楚了第一部分,但是,我在第二部分遇到了困难。当我知道它在 VM 上运行时,下面的代码总是返回“进程未运行”。我认为问题在于不止一个 PowerShell 进程。有人可以指导我吗?

$process = Invoke-Command -ComputerName "vmonnetwork" -ScriptBlock { Get-Process -name "powershell" -IncludeUserName } | Select-Object UserName

if ($process -eq "userA") {
    Write-Host "Process is running"
}
else {
    Write-host "Process is not running"
}

标签: powershell

解决方案


尝试对您的代码进行以下更改之一(不能同时更改两者):

更改if ($process -eq "userA")if ($process.UserName -eq "userA")

或者

更改Select-Object UserNameSelect-Object -ExpandProperty UserName


推荐阅读