Powershell ForEach-Object:无法绑定参数

我正在尝试使用此代码获取进程的所有者:

(Get-WmiObject -class win32_process | where{$_.ProcessName -eq 'explorer.exe'}).getowner() | Foreach-Object user | out-string 

这在Windows 8下工作良好,但在Windows 7中,我收到以下消息:

ForEach-Object:无法绑定参数'Process'。 无法将“System.String”types的“用户”值转换为键入“System.Management.Automation.ScriptBlock”。 在C:\ Program Files(x86)\ Advanced Monitoring Agent GP \ scripts \ 9660.ps1:1 char:108 +(Get-WmiObject -class win32_process |其中{$ _。ProcessName -eq'explorer.exe'})。 getowner()| Foreach-Object <<<<用户| out-string + CategoryInfo:InvalidArgument:(:) [ForEach-Object],参数BindingException + FullyQualifiedErrorId:CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand

请修改用户迭代器并尝试7和8:

 (Get-WmiObject -class win32_process | where{$_.ProcessName -eq 'explorer.exe'}).getowner() | Foreach-Object {$_.user } | out-string 

你可以用换行符来做到这一点:

 gwmi win32_process | where ProcessName -Match "explorer" | foreach {$_.GetOwner().User | Out-String} 

没有

 gwmi win32_process | where ProcessName -Match "explorer" | foreach {$_.GetOwner().User} 

记得把你的foreach脚本包装在{}里面。

为了完整起见,我会说这是用Powershell 3.0完成的,因此没有{}作为where-object cmdlet,没有$_用于ProcessName属性。