Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to put in multiple values in a where-object filter

Status
Not open for further replies.

andyferris

IS-IT--Management
Sep 10, 2010
6
IM
I have some code:

Get-ADGroupmember -Identity Servers|Select-Object -ExpandProperty name|Sort-Object

Which returns a simple list of members of the "Servers" group.

A foreach loop then does other stuff with that list (finds stopped services and restarts them)

What I would like to do is to give myself the option of sometimes excluding some servers from that list.

I know I could put in a where-object{$_.name -ne 'server1' -and....... } etc, but the list changes each time and I would like to automate this with a scheduled task so to make it easier I wonder if I could use some kind of variable. something along the lines of:

$excludedservers="server1","server2"
Get-ADGroupmember -Identity Servers|Where-Object{$_.name -ne $excludedservers}|Select-Object -ExpandProperty name|Sort-Object

This doesn't work though, it still produces the full list.

Can anyone point me in the right direction? maybe a foreach is needed? I cant see how to do it.

Thanks
 
Slight modification to your filter script block on the Where-Object. You are looking to compare a single value ($_.name) to ensure it is not in the array of excluded servers

[pre]Get-ADGroupmember -Identity Servers |
Where-Object{$_.name -notin $excludedservers} |
Select-Object -ExpandProperty name |
Sort-Object[/pre]

Make your code readable and put line breaks in where there is a logical separator in the PowerShell statement. If you end a line at the pipe character '|' PowerShell will know that a pipeline exists and there is more code to follow.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top