I have a simple question regarding code blocks within statements, and variables. My script gathers user input and creates a string that can be used in a powershell statement later on.
$filter = @()
While ($filter[-1] -ne "end") {
$filter += read-host 'Type the name of an OU you want to filter or type "end" to start the script'
if ($filter[-1] -eq "end") {
break
}
$strFilter += "`$_`.DistinguishedName -notlike `"*" + $filter[-1] + "*`" "
$strFilter += "-and "
}
$strFilter = $strFilter.SubString(0,$strFilter.length-5)
Basically the user will type in however many words, and those words will be appended to the string "$_.DistinguishedName -notlike "*<WORD>*"" and throw them together with -and until the last word entered.
That part works fine, it’s using this generated string to gather information that doesn’t seem to work; I have a feeling it’s something very simple that I’m just missing.
For example:
$computers = get-adcomputer -Filter 'ObjectClass -eq "Computer"' -properties "OperatingSystem","CanonicalName","Description"
$filteredComputers = $computers | where-object { $strFilter }
$filteredComputers returns the same results as $computers which leads me to believe that the Where-object statement with my string variable isn’t doing anything.
Appreciate any help, thanks.
The
Where-Objectscriptblock should evaluate to a Boolean value (or something that can be coerced to a Boolean value). You’re providing just a string which, if not empty, PowerShell will coerce to a Boolean $true. Try something like this instead:This uses a nested pipeline to walk each filter term and apply it to the current object’s DistinguishedName – which we had to stash because in the nested pipeline
$_takes on the value of the current $strFilter array element. If any of those pass theliketest then the count will be greater than zero and won’t get passed down the pipeline. Only those that don’t match any like (count == 0) should get passed on down the pipeline.Here’s an example of this approach: