Filter output (where-object) from variable

Deadly 提交于 2021-02-11 14:12:39

问题


I am running a test on servers with the following line:

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

I would like to create a variable like this:

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

and send this to Where-Object. Can I do this?

Sune:)

EDIT: After some R/T (research and trying:)) I found out that I can do this:

$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

But.. I would REALLY like if one could specify services to be excluded in the following manner: "service1","service2","service3"

As always, all help is greatly appreciated!!


回答1:


Yeah you can just do:

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

like you wanted and do the following in the where-object:

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



回答2:


You can do that with a WMI filter (runs faster), and since you only select properties there's no need to create new objects, use the 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


来源:https://stackoverflow.com/questions/8685989/filter-output-where-object-from-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!