问题
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