Where-object -or not working - powershell

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

Related

Issue with powershell output ad-computer foreach

$computers = Get-ADComputer -Filter * -Properties * | Where-Object {$_.Name -like "LT*" -or $_.Name -like "PC*" -or $_.Name -like "MC*"} | Select name,lastlogondate
"You have [{0}] computers in domain [{1}]" -f $computers.count, (get-addomain).dnsroot
$today = Get-Date
$monthago = $today.AddDays(-30)
"Looking for systems that have not logged in since $monthago"
foreach ($computer in $computers)
{
if ($computer.lastlogondate -lt $monthago)
{"Computer [$computer] suspect"
"last logon $($computer.lastlogondate)"
""}
}
returns the following result:
Computer [#{name=lt020367; lastlogondate=10/23/2019 11:45:38}] suspect
last logon 10/23/2019 11:45:38
Can someone possibly tell me why my output is resulting in [#{ and how to resolve?
by get-adcomputer [...] | Select name,lastlogondate you are creating an object. To output properties of those objects, simply use:
"Computer [$($computer.name)] suspect"
"last logon $($computer.lastlogondate)"
By the way:
Getting all * properties is not ideal. Always filter as early as you can: -properties lastlogondate (name is always returned). Same goes for -filter "name -like 'LT*' -or name -like 'PC*' -or name -like 'MC*'".
Also be careful as lastlogondate of computer objects in AD is not synced between domain controllers.

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

Powershell to get accounts with passwords older than "$"

I am trying to get a list of accounts with passwords that are older than lets say 90 days but something is not working right and I am not sure why.
Get-ADUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet,samaccountname,passwordlastset | Where-Object {$_.PasswordLastSet -gt ($_.PasswordLastSet).adddays(1)} | select Name,samaccountname,passwordlastset
This is what i got so far but if I run it as is it returns 0 results. I know there are passwords that are older than one day, mine is one of them. Any help is appreciated.
Per your realization in the comments you should compare the PasswordLastSet field to today's date less 90 days as follows:
Get-ADUser -Filter 'Enabled -eq $True' -Properties PasswordLastSet | Where-Object {$_.PasswordLastSet -lt (Get-Date).adddays(-90)} | select Name,SamAccountName,PasswordLastSet
Use -lt for older passwords, or -gt for newer passwords.
You can try this,if you wana export remove #
$DaysAgo=(Get-Date).AddDays(-90)
$params = #{
"filter" = 'Enabled -eq $true -and passwordlastset -lt $DaysAgo'
"Properties" = "Displayname",
"passwordlastset",
"samaccountname"
}
Get-ADUser #params |select displayname,samaccountname,passwordlastset #| export-csv C:\result.csv -nti

Powershell where-object syntax - Hyphen in attribute

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"

List users who have an empty description field in PowerShell

I'm trying to get a list of Active Directory users who have no description set.
I start with getting a list of users:
$users = Get-AdUser -Filter {(Enabled -eq "True" )} -Properties Description
And then I tried these options (to get list of users with no description):
$NoDescrUsers = $users | Where-Object {$_.Description -eq ""}
$NoDescrUsers = $users | Where-Object {$_.Description -eq ''}
$NoDescrUsers = $users | Where-Object $_.Description -eq ""
$NoDescrUsers = $users | Where-Object {$_.Description -match ""}
$NoDescrUsers = $users | Where-Object -not {$_.Description -like '*'}
None of these work (or it returns 0 in a foreach or returns everyone). What should my command look like?
I'm not sure why none of the options you tried worked (it seems like they should). Having Googled the general consensus seems to be that you can do this successfully (and more efficiently) within the initial -filter. For example:
$NoDescrUsers = Get-AdUser -Filter {(Enabled -eq "True" ) -and (description -notlike '*')} -Properties Description
If you filter description -like or -notlike
'*'
) that means you'll take any character (or not).
If you want filter only empty description in your AD request, you could do:
$NoDescrUsers = Get-AdUser -Filter {(Enabled -eq "True" ) -Properties Description
if ($NoDescrUsers.Description -eq $null)
{write-host "no description"}