Powershell脚本,用于查找进程并返回进程,计算机名和用户名

时间:2012-11-09 11:51:03

标签: powershell

我想在运行特定程序的用户之后搜索十个终端服务器。我希望输出包括进程,计算机名和用户。

这个命令基本上可以做我想要的:

Invoke-Command -ComputerName (Get-Content .\test-servers.txt) -ScriptBlock { get-wmiobject win32_process|where{$_.name -eq "iexplore.exe" }|select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

name         PSComputerName owner 
----         -------------- ----- 
iexplore.exe mrdsh-test     dojo03
iexplore.exe mrdsh-test     dojo03
iexplore.exe mrdsh-test     baob12
iexplore.exe mrdsh-test     baob12

但是当我尝试创建一个以流程作为参数的脚本时,我无法让它工作。

CmdletBinding()]
Param (
[parameter(mandatory=$true)][string]$process
)

Invoke-Command -ComputerName (Get-Content .\test-servers.txt) -ScriptBlock { get-wmiobject win32_process | where{param($process)$_.name  -eq $process } | select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

我还没有设法将$ process参数发送到调用该命令的服务器。我该怎么办?或者是否有更简单的方法来查找流程和返回流程,计算机名和用户名?

1 个答案:

答案 0 :(得分:1)

你的where scriptblock中有param($ process),你没有设置它,所以它将是空的。

修改

根据要求,在我的机器上执行以下工作:

[CmdletBinding()]
Param (
[parameter(mandatory=$true)][string]$process
)

Invoke-Command -ScriptBlock { get-wmiobject win32_process | where{ $_.name  -eq $process } | select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

它也适用于Powershell版本1:

powershell -version 1.0 -noprofile -Command ".\test.ps1 -process 'chrome.exe'"

工作正常。