Powershell Filter ADgroups the right way - powershell

Hi im trying to Filter AD-Groups by a string i defined in a variable:
$groupname="string"
Get-ADGroup -filter {GroupCategory -eq "security" -and Name -like ($sgroup_name+"*")}
How do i do this the right way?

String expansion doesn't work well with the -Filter parameter when passing it a script block - use a string filter instead:
$groupname = "string"
Get-ADGroup -Filter "GroupCategory -eq 'security' -and Name -like '${groupname}*'"

Related

Why can't the variable be passed?

I have the following problem. I get no output with the following command and no error message either. However, if I take the line by itself and replace $n with the username or just part of it, it works.
$n = Read-Host -Prompt "Benutzer eingeben"
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and Name -like "*$n*"} -Properties Name, DisplayName, msDS-UserPasswordExpiryTimeComputed | Select-Object -Property Name, Displayname,#{Name="Expiration Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
I would be grateful for a tip
If curly braces are used to enclose the filter, the variable(in this case it's $n) should not be quoted.
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and Name -like $n} -Properties Name, DisplayName, msDS-UserPasswordExpiryTimeComputed | Select-Object -Property Name, Displayname,#{Name="Expiration Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
Here is the relevant part from the documentation.
if the filter expression is double-quoted, the variable should be
enclosed using single quotation marks: Get-ADUser -Filter "Name -like '$UserName'". On the contrary, if curly braces are used to enclose the
filter, the variable should not be quoted at all: Get-ADUser -Filter {Name -like $UserName}.

Get-ADUser with multiple filters & variables

I'm trying to get AD users into a variable using multiple filters. However one of the filters has variables in it & I can't get it to work... I have searched for similar issues & tried applying those but nothing seems to work.
$FilterBase = "department"
$Filter = "IT"
$ADusers = Get-ADUser -ResultSetSize $null -SearchBase "OU=Users,DC=mydomain,DC=com" -Properties * -Filter {(Enabled -eq $True) -and ($FilterBase -like $Filter) -and (cn -notlike ""SMB_*"")} |
Select-Object distinguishedName |
Sort-Object distinguishedName
I'm trying to fill $ADusers with all enabled users whose commonname doesn't start with "SMB_" (don't ask) & where the department is IT. I used -like to prevent issues if the values in AD would have different casings (uppercase, lowercase, mixed case, ...).
The reason that I'm using variables for this is because in the end the script will be dynamic. At some point $FilterBase is going to be "company" instead of "department" and $Filter is going to be "HR" instead of "IT" etc...
But I just can't seem to get it to work:
Get-ADUser : Error parsing query: '(Enabled -eq $True) -and ($FilterBase -like $Filter) -and (cn -notlike ""SMB_*"")' Error Message: 'syntax error' at position: '74'.
At line:4 char:12
I have tried using quotes around the variables like "$Filter", "$($Filter)", ' $Filter ' but alas. And I know it's not best practice to use variables in Filter but I can't think of any other way to accomplish this.
Any suggestions?
the error has the key to the answer. I'm sure I'll find this again and use it myself because I look this up every year or so...
Error parsing query: '(Enabled -eq $True)...'
In this case the filter needs a simple string 'True' which the variable $True does equal.
Two options will work, either
Enabled -eq 'True'
or
Enabled -eq '$True'
but
Enabled -eq $True
will not.
This should work
Replaced the braces with double quotes so inside them the variables still parse
Put single quotes around all strings and variables that resolve into strings
'$True'
'$Filter'
'SMB_*'
$FilterBase = "department"
$Filter = "IT"
$ADusers = Get-ADUser -ResultSetSize $null -SearchBase "OU=Users,DC=mydomain,DC=com" -Properties CN -Filter "(Enabled -eq '$True') -and ('$FilterBase' -like '$Filter') -and (CN -notlike 'SMB_*')" |
Select-Object distinguishedName |
Sort-Object distinguishedName
Important to note the above syntax highlighting will make the sample above look wrong because it misses the tokens like $FilterBase and $Filter when there are inside single quotes inside double quotes. Remember that single quotes are just apostrophes when inside double quotes, therefore the tokens should be colored differently and not look like strings.
> "('$FilterBase' -like '$Filter')"
('department' -like 'IT')
Paste a sample like above and see what it resolves to - best way to figure it out.
its just simply syntax error.
$enabled = 'Enabled'
$EnabledTrueOrFalse = $true
$SN = 'Surname'
$surname = "Doe"
$OU = "OU=Users,DC=mydomain,DC=com"
Get-ADuser -filter{$enabled -eq $EnabledTrueOrFalse -and $SN -eq $surname} -SearchBase $OU -Properties * | Select-Object distinguishedName | Sort-Object distinguishedName
read more about it here
Thanks for the tips guys. I couldn't get it to work with multiple filters so I moved some filters to the where clause.
My current (working) code is now:
$FilterBase = "department"
$Filter = "IT"
$ADusers = Get-ADUser -ResultSetSize $null -SearchBase "OU=Users,DC=mydomain,DC=com" -Properties * -Filter "$FilterBase -like `"$Filter`"" |
Where {$_.Enabled -eq $True -and $_.CN -notlike "SMB_*"} |
Select-Object distinguishedName |
Sort-Object distinguishedName

How can I cast an AD Attribute in a filter condition when calling Get-ADUser in PowerShell?

What I am trying to do:
Return a list of AD users filtered by the date stored in an AD attribute using PowerShell.
The problem
The date I want to filter on is stored in an AD attribute with a string data type, specifically extensionAttribute12. This is non-negotiable with the people I am writing the script for.
I'm having trouble getting the syntax right in my filter to cast that string to a date before the comparison.
Here's my non-working code:
Import-Module ActiveDirectory
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy')
$OU = "OU=PIV_Users,OU=FakeOU,DC=fake,DC=com"
$30Days = (Get-Date).AddDays(-30)
Get-ADUser -SearchBase $OU -SearchScope OneLevel -Filter {(extensionAttribute12 -notlike "*" -or extensionAttribute12 -le $30days) -and (enabled -eq $true) -and (whencreated -lt $30Days)} -Properties * |
Select-Object Name, samAccountName, extensionAttribute12, whenCreated, enabled, employeeType
This is the error:
Get-ADUser : Invalid type 'System.DateTime'.
Parameter name: extensionAttribute12
At line:9 char:1
I tried adding a cast as follows
... -or **[DateTime]extensionAttribute12** -le $30days) ...
Which gave me this error:
Get-ADUser : Error parsing query: '(extensionAttribute12 -notlike "*" -or [DateTime]extensionAttribute12 -le $30days) -and (enabled -eq $true) -and (whencreated -lt $30Days)'
Error Message: 'syntax error' at position: '40'.
At line:9 char:1
To my knowledge it's not possible to cast attributes to a different type in an AD search string. Despite the scriptblock-like notation the argument to the parameter -Filter is essentially a query string.
What you can do is do the filtering via Where-Object after fetching the objects. That's not optimal (because your AD query will return more objects than it needs to), but in this case I don't see another way. Make sure, however, that you only move those parts of the filter to the Where-Object that won't work otherwise, so that Where-Object doesn't need to process all user objects.
Get-ADUser-Filter {extensionAttribute12 -notlike '*' -and enabled -eq $true -and whencreated -lt $30Days} ... |
Where-Object { [DateTime]extensionAttribute12 -le $30days } |
...

Get-ADUser for not exact username

The script below lists some user details, it works only in case I've entered the EXACT user name. Is there a method I could use to get results if I type a partial username?
I mean if for example I enter "elibukin" or "eli.buk" instaed of "eli.bukin" witch is the correct username.
do {
Write-Host "Who r we looking for ? (type EXIT when u done)"
$User = Read-Host
Get-ADUser $User -Properties * |
fl empl*,title, sam*, disp*, mail*, manager*, depa*, giv*, l, last*,
logon*, when*
} until ($user -eq "exit")
I would use -LDAPFilter with ambiguous name resolution (ANR).
Get-ADUser -LDAPFilter "(anr=smith)"
See https://support.microsoft.com/en-us/kb/243299 for more information about ANR.
I have actually worked on a script much like this. I used the -like operator to accommodate partial matches. However, this might give you more than one result.
Get-ADUser -Filter ("SamAccountName -like '*$user*'")
Or use something of this format to narrow down your result:
Get-ADUser -Filter ("SamAccountName -like '*$user*' -and Name -like '*$FirstName*' -and Surname -like '*$Lastname*'")
Use -or instead of -and for a broader result.
If you want fuzzy matching use the parameter -Filter with the -like operator:
do {
$user = Read-Host -Prompt 'Who are we looking for (type EXIT when done)'
if ($user -ne 'exit') {
Get-ADUser -Filter "SamAccountName -like '*$User*'" -Properties * |
Format-List empl*,title, sam*, disp*, mail*, manager*, depa*, giv*, l,
last*, logon*, when*
}
} until ($user -eq "exit")

Using "-Filter" with a variable

I try to filter out something like this:
Get-ADComputer -Filter {name -like "chalmw-dm*" -and Enabled -eq "true"} ...
This works like a charm and gets exactly what I want...
Now I want the "name -like ..." part as a variable like this:
Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"} |
I checked several questions (for example, PowerShell AD Module - Variables in Filter), but this isn't working for me.
I tried it with the following:
$nameRegex = "chalmw-dm*"
$nameRegex = "`"chalmw-dm*`""
And also in the Get-ADComputer command with those ' and without.
Could anyone give me some hints?
You don't need quotes around the variable, so simply change this:
Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}
into this:
Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}
Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:
Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"
Related. Also related.
And FTR: you're using wildcard matching here (operator -like), not regular expressions (operator -match).
Add double quote
$nameRegex = "chalmw-dm*"
-like "$nameregex" or -like "'$nameregex'"
Try this:
$NameRegex = "chalmw-dm"
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}
Or
-like '*'+$nameregex+'*'
if you would like to use wildcards.