Hi
I am trying to build a script for creating distribution groups, but I would require me to be able to do different filters.
eg. one group could be if country eq UK, or a group where country eq UK, and department eq 999 and so on in many combinations.
oc. this has to be handled by inputting different parameters.
My question is if any have a idea on how to build the -filter in the Get-ADUser, I started with a "if" based on if country is empty or not, but realized, I need to have a lot of combinations, a wonder if It could be build based on the input. Then I started with another if block, building a part of the filter string. Like City -eq $City. So now my problem is, how to put these together, because, now I need to add the correct number of "AND"'s
Any have a smart way of doing this.
This is a small test script, showing my idea.
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position = 0)]
[string]$DGroup,
[Parameter(Mandatory=$False)]
[string]$departmentNumber,
[Parameter(Mandatory=$False)]
[string]$country,
[Parameter(Mandatory=$False)]
[string]$city
)
##Modules
Import-Module ActiveDirectory
##Variables
$Searchbase = "DC=XXXX,DC=Local"
if ($departmentNumber -eq "")
{
$FilterDep="departmentNumber -eq $departmentNumber"
}
else
{
$FilterDep=""
}
if ($country -eq "")
{
$FilterCountry="countryCode -eq $country"
}
else
{
$FilterCountry=""
}
if ($city -eq "")
{
$FilterCity="City -eq $City"
}
else
{
$FilterCity=""
}
if ($country -eq "")
{
$userOU = Get-ADUser -Filter 'departmentNumber -eq $departmentNumber' -SearchBase $Searchbase -Properties @("homedirectory","name","accountExpires","AccountExpirationDate","lastlogondate")
}
else
{
$userOU = Get-ADUser -Filter 'departmentNumber -eq $departmentNumber -and countryCode -eq $country' -SearchBase $Searchbase -Properties @("homedirectory","name","accountExpires","AccountExpirationDate","lastlogondate")
}
Write-Host Numbers of parameters $psboundparameters.count
Write-Host Group is $DGroup
Write-Host Deparetmentnumber is $departmentNumber
Write-Host Country is $country
Write-Host City is $city