Use array of strings for comparing in Where-Object in PowerShell

梦想与她 提交于 2019-12-13 11:11:07

问题


I have a user list of Active Directory that I retrieve this way:

$users = Get-AdUser -Filter {(Enabled -eq "True" )} -Properties Description 

The problem is that I have a specific set of users that is based in their description:

  • Admins
  • Secretaries
  • Mail men

What I do is create sublists like this:

$Admins = $users | Where-Object Description -eq 'Administrator'

The problem however is, that there is no standardization. The person who creates an user can write 'Admin' or 'Administrator' or 'adm',... which causes my sublist not to contain all users that are an admin.

What I did is that I created an array of strings:

$Admin_User_Strings = @("adm", "admin", "administrator")

And I wanted to use this array in my sublist but this appearantly doesn't work:

$Admins = $users | Where-Object $Admin_User_Strings -contains Description 

I get the errror:

Where-Object : A positional parameter cannot be found that accepts argument 'System.Object[]'.

So my question is, how can I let the following line:

$Admins = $users | Where-Object Description -eq 'Administrator'

accept more ways of 'Administrator' inputs?


回答1:


You have several options:

$users | Where-Object {$Admin_User_Strings -contains $_.Description}

or: $users | Where-Object $_.Description -in $Admin_User_Strings

or: $users | Where-Object $_.Description -match "adm|admin|administrator"



来源:https://stackoverflow.com/questions/43408185/use-array-of-strings-for-comparing-in-where-object-in-powershell

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