简体   繁体   中英

Filter output (where-object) from variable

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!!

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  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM