从变量中过滤输出(where-object)

时间:2011-12-31 02:52:53

标签: powershell active-directory wmi where-clause

我正在使用以下行在服务器上运行测试:

Get-WmiObject Win32_Service -ComputerName "myserver" -Filter "State='Running'" |
where-object ??? }| Foreach-Object {
                New-Object -TypeName PSObject -Property @{
                    DisplayName=$_.DisplayName
                    State=$_.State
                } | Select-Object DisplayName,State
            # Export all info to CSV
            } | ft -AutoSize

我想创建一个这样的变量:

$IgnoreServices = '"Wireless Configuration","Telephony","Secondary Logon"

并将其发送到Where-Object。我可以这样做吗?

淑娜:)

编辑: 经过一些R / T(研究和尝试:))我发现我可以做到这一点:

$IgnoreServices = {$_.DisplayName -ne "Wireless Configuration" 
-and $_.DisplayName -ne "Telephony" -and $_.DisplayName -ne "Secondary Logon" 
-and $_.DisplayName -ne "Windows Event Collector"}

Get-WmiObject Win32_Service -ComputerName "myserver" -Filter   "State='Running'"|        where-object $IgnoreServices | Foreach-Object {
                # Set new objects for info gathered with WMI
                New-Object -TypeName PSObject -Property @{
                    DisplayName=$_.DisplayName
                    State=$_.State
                } | Select-Object DisplayName,State
            # Export all info to CSV
            } | ft -AutoSize

但是......如果可以通过以下方式指定要排除的服务,我真的很喜欢:     “服务1”, “服务2”, “服务3”

与往常一样,非常感谢所有帮助!!

2 个答案:

答案 0 :(得分:5)

是的,你可以这样做:

$IgnoreServices = "Wireless Configuration","Telephony","Secondary Logon"

就像你想要的那样,在where-object中执行以下操作:

where-object { $IgnoreServices -notcontains $_.DisplayName  }

答案 1 :(得分:2)

您可以使用WMI过滤器(运行速度更快),并且由于您只选择属性而无需创建新对象,因此请使用Select-Object cmdlet instaed:

$filter = "State='Running' AND Name <> 'Wireless Configuration' AND Name <> 'Telephony' AND Name <> 'Secondary Logon'"

Get-WmiObject Win32_Service -ComputerName myserver -Filter $filter | Select-Object DisplayName,State