Powershell where-object syntax - Hyphen in attribute - powershell

I'm using the below to target only relevant users.
Get-ADUser -Filter * -SearchBase $TargetOU -Properties * | Where-Object {$_.adminDescription -eq "Azure_Sync" -and $_.proxyAddresses -notlike "sip*" -and $_.sn -ne $null -and $_.msRTCSIP-PrimaryUserAddress -ne $null
However, it's not liking the last one $_.msRTCSIP-PrimaryUserAddress. The "-" is breaking things here so how do I go about using this attribute in the same way as the others?

You can add quotes around the property like
$_."msRTCSIP-PrimaryUserAddress"

Related

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 } |
...

Powershell iterate through collection in where-object

Forgive me in advance as I may not be defining things correctly here:
I have a script that queries Active Directory for users in a specific OU while excluding a dozen or so OUs within that OU. The script works, but it's kind of messy as I'm declaring 13 variables representing the various OUs and referencing them in where-object. There's also an existing foreach loop as I'm querying more than one domain. I'd like to find a way to reference all the OU's I'm excluding from the query in a single collection or array or whatever and loop through it in my where-object to avoid having to reference 13 variables in the where-object. Can anyone point me in the right direction? (Code below excludes the OU variable defintions)
Existing Code:
(Get-ADForest).domains | foreach {
Get-ADUser -filter {Enabled -eq $True} -properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ |
where-object {$_.Title -notmatch "Volunteer" -and $_.DistinguishedName -notmatch $excludeOU1 -and $_.DistinguishedName -notmatch $excludeOU1 -and $_.DistinguishedName -notmatch $excludeOU2 -and
$_.DistinguishedName -notmatch $excludeOU3 -and $_.DistinguishedName -notmatch $excludeOU4 -and $_.DistinguishedName -notmatch $excludeOU5 -and $_.DistinguishedName -notmatch $excludeOU6 -and
$_.DistinguishedName -notmatch $excludeOU7 -and $_.DistinguishedName -notmatch $excludeOU8 -and $_.DistinguishedName -notmatch $excludeOU9 -and $_.DistinguishedName -notmatch $excludeOU10 -and
$_.DistinguishedName -notmatch $excludeOU11 -and $_.DistinguishedName -notmatch $excludeOU12 -and $_.DistinguishedName -notmatch $excludeOU13 }
}
Thanks!
You could use a regex to use with notmatch.
[regex]$excluderegex = "^(excludeOU1|excludeOU2|excludeOU3)$"
(Get-ADForest).domains | foreach {
Get-ADUser -filter {Enabled -eq $True} -properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ |
where-object {$_.Title -notmatch "Volunteer" -and $_.DistinguishedName -notmatch $excluderegex}
}
You can put anything you like inside the Where filter expression:
$excludes = $excludeOU1,$excludeOU2,$excludeOU3,$excludeOU4,$excludeOU5,$excludeOU6,$excludeOU7,$excludeOU8,$excludeOU9,$excludeOU10,$excludeOU11,$excludeOU12,$excludeOU13
Get-ADUser -Filter {Enabled -eq $true} -Properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ | Where-Object {
$_.Title -notmatch 'Volunteer' -and $(&{
foreach($exclude in $excludes)
{
if($_.DistinguishedName -match $exclude)
{
return $false
}
}
return $true
})
}
You could use the Select-Object cmdlet in your pipeline to add a new "calculated property" to your Get-ADUser data that holds just the OU of the user. The Where-Object call could then simply use a -notin operator.
In my opinion, this would make the code a little more readable. More info here:
Select-Object Calculated Properties
Notin Operator

Where-object -or not working

Alright - so the company i work for has bought out quite a few domains. Each domain has a different naming schema. (ex: john.smith, jsmith) - When we terminate someone, i'd like to automate disabling their accounts in every domain.
This script works perfectly fine until I add the 'or' statement in where-object cmdlet.
$user1 = "John.smith"
$user2 = "Jsmith"
get-aduser -Filter * | Where-Object {{$_.samaccountname -eq "$User1"} -or {$_.samaccountname -eq "$user2"}}
If i take out the or statement - it finds the user. If i put the or statement in, it just returns every user in my domain.
I've also tried avoiding the -or, and went with a if,else statement:
$user1 = "john.smith"
$user2 = "jsmith"
$result = Get-ADUser -filter * | Where-Object {$_.samaccountname -eq "$user1"}
if($result = $error) {Get-ADUser -Filter * | Where-Object {$_.samaccountname -eq "$user2"}}
This doesn't return an error - it just doesn't return anything (might be doing the if statement wrong - but why no error?
Thank you,
You have an extra set of brackets inside your Where-Object. What you were going for would work with parenthesis, but it'll work just the same without any:
get-aduser -Filter * | Where-Object {$_.samaccountname -eq "$User1" -or $_.samaccountname -eq "$user2"}

Powershell Lync/AD syntax

I've been racking my brain trying to figure out why the synatx below is wrong. I'm fairly new to powershell, so any help would be appreciated.
The issue seems to be with the $false in the filter variable, without that it works.
$BU = 'corp','sales'
$filter="(extensionattribute6 -like '*514' -or extensionattribute6 -like '*66048') -and msRTCSIP-UserEnabled -eq $false"
$BU | % {get-aduser -Properties displayname -Filter $filter -SearchBase 'ou=users,ou=$_,ou=Business Units,dc=biz,dc=com' -SearchScope Subtree}
Use single quotes around the content for $filter
$filter='(extensionattribute6 -like "*514" -or extensionattribute6 -like "*66048") -and msRTCSIP-UserEnabled -eq $false'
Double quotes will replace variables with their value, so it searches for msRTCSIP-UserEnabled -eq False (which throws a syntax error) instead of msRTCSIP-UserEnabled -eq $false.