PowerShell- Get-ADUser Filter Issue - powershell

New to PowerShell and am having issues with Get-ADUser -Filter. I believe the issue has to do with the -Filter
$TC_TellerID_Array = #()
$TC_TellerID_Array = Import-Csv "C:\Designer.csv"
$ADUsersArray = #()
$ADUsersArray=get-aduser -filter * -Properties * | select Name, SamAccountName, extensionAttribute1, Enabled | where extensionAttribute1 -ne $null
Foreach ($User in $ADUsersArray)
{$TrimmedTeller = ($User.extensionAttribute1).Trim()
Foreach ($TC_TellerID in $TC_TellerID_Array)
{
Get-ADUser -Filter "'$TrimmedTeller' -eq '$TC_TellerID.TellerID'" -Properties * | Select Name,SamAccountName,extensionAttribute1, Enabled
}
}

Those single quotes are forcing a literal string. As #JosefZ pointed out. You would also want to pull your value of TellerID out using a SubExpression . Try changing your code to look like
Get-ADUser -Filter {$TrimmedTeller -eq $($TC_TellerID.TellerID)} -Properties * | Select Name,SamAccountName,extensionAttribute1, Enabled

Related

How to user where-object with a variable input

Ok so I am trying to use a variable to make up a where statement on a get-aduser command.
This is what I am trying to emulate which works:
get-aduser -filter * | where { $_.DistinguishedName -like "*Users,DC*" }
Note the are asterix before and after the User,DC. Not showing for some reason.
So here is what I have in the script which returns nothing:
$SearchBase = (get-addomain).DistinguishedName
$DefaultUsersOU = "*OU=Users," + $SearchBase
get-aduser -Filter * -Properties lastLogonTimeStamp -Searchbase "$($SearchBase)" | where-object { $_.DistinguishedName -like $DefaultUsersOU }
Found a similar article on here Where object as variable but if I apply that thinking to the DistinguishedName field it doesnt work either.

Export-Csv doesn't show AD group name while exporting its members

I have a list with AD groups in a CSV file: Input_ADGroup.csv
Column A looks like this:
CN
ADgroup1
ADgroup2
I already have some code which list all the users of the groups in the output.csv file, however I am missing the ADgroup name. So it is unclear which users are member of which group.
$Manager = #{Name = "Manager"; Expression = {%{(Get-ADUser $_.Manager -Properties DisplayName).DisplayName}}}
$Manager_Location = #{Name = "Manager_Location"; Expression = {%{(Get-ADUser $_.Manager -Properties Office).Office}}}
$Fields = #(
'SamAccountName'
'CN'
'DisplayName'
'Office'
'mail'
'Department'
$Manager
$Manager_Location
)
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
So is it possible to get a column which shows the "source-ADgroup"... or another format which breaks the list with the ADGroup name or something?
IMO my other suggested solution is more efficient applyig the same CN from the input:
$Data = ForEach($CN in (Import-Csv -Path H:\Test\Input_ADGroup.csv).CN) {
Get-ADGroup -Filter "CN -eq '$CN'" -Properties CN -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -Properties * | Select-Object ($Fields+#{n="Group";e={$CN}})
}
$Data
$Data | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
As you already have AD group name in $_, you can add one more calculated property to your Select-Object by changing this:
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
to this (saving first group name to variable to not mix up with $_ used later in pipeline):
$GroupName = $_.CN
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$GroupName}})
Credits to #LotPings and #Maikel for pointing out the issue with incorrect $_ usage in comments
NOTE: remember about brackets, otherwise you'd receive an error like:
Select-Object : A positional parameter cannot be found that accepts argument n="Group";e={$GroupName}
#Lotpings #robdy - Thanks for your input, I got it working so many thanks. See code below
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties CN -PipelineVariable name -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$name}})
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
One last note: The AD group gets displayed as CN=Groupname,OU=...OU=… etc
I couldn't get it to show just "Groupname" but this really is not an issue.

Find security and distribution groups with owners whose account is disabled

I'm looking for some guidance on creating a powershell script that will check security and distribution groups from specific OU's and see if the owner is a user who's disabled.
We have lots of old groups in our AD created by ex employees that need to be cleaned up.
This is what i've started with.
$managedByGroups = get-adgroup -filter 'groupCategory -eq "Distribution"' -SearchBase "OU=SydExchangeGroups,OU=SydGroups,OU=Sydney,DC=my,DC=org,DC=biz" -Properties distinguishedname, managedby | select sAMAccountName, managedby
$disabledUsers = Get-ADUser -Filter {Enabled -eq $false} -SearchBase "OU=SydDisabledUsers,OU=SydMisc,OU=Sydney,DC=my,DC=org,DC=biz" | select distinguishedname
foreach ($group in $managedByGroups){
if($managedByGroups.managedby -eq $disabledUsers.distinguishedname)
{
write-output
}
}
Thanks
There are a number of issues with your if block:
you are looping through $managedByGroups, but you are never using that variable (it should be $group.managedby)
you are trying to compare 1 element with a list of elements, in this case consider using -in operator instead of -eq.
you should treat the case when there is no value for managedby attribute, in case you do not get the desired results.
An alternative to your code may is below.
I'm first getting the list of managedby users, then i'm looping though each entry, and if it is not null, we try to do a get-aduser filtering by enabled status and the distinguishedname.
$DisabledManagedBy variable will contains ADUser objects which are disabled.
$grp = get-adgroup -filter 'groupCategory -eq "Distribution"' -Properties ManagedBy,DistinguishedName
$DisabledManagedBy = foreach ($item in $grp.ManagedBy) {
if ($item) {
Get-ADUser -Filter {Enabled -eq $false -and DistinguishedName -like $item} -Properties DistinguishedName
}
}
I worked this out eventually by doing the following:
$myDisabledUsers = #()
$date = get-date -format dd-MM-yyyy
$managedSydGroups = Get-ADGroup -Filter * -Properties * -Searchbase "OU=SydExchangeGroups,OU=SydGroups,OU=Sydney,DC=my,DC=biz,DC=org" | where {$_.managedby -ne $null} | select name, managedby
$disabledSydUser = Get-ADUser -Filter * -SearchBase "OU=SydDisabledUsers,OU=SydMisc,OU=Sydney,DC=my,DC=biz,DC=org" | where {$_.enabled -eq $false} | select -ExpandProperty distinguishedname
$disabledOwners = foreach($group in $managedSydGroups)
{
$managedByString = [string]$group.managedby
if($disabledSydUser -contains $managedByString)
{$myDisabledUsers += $group}
}

How to use pipeline input in a foreach loop?

Trying to run a command in a foreach loop that contains different search locations, e.g.:
$ous ='ou=Staff,dc=example,dc=local', 'ou=Managers,dc=example,dc=local'
$colItems = $ous | ForEach { Get-ADUser -Filter * -SearchBase "ou=Example,dc=example,dc=local" -Properties whenCreated | select -Property Enabled,Name,SamAccountName,whenCreated }
I want to replace the OU in the search query each time
"ou=Example,dc=example,dc=local"
If you use a pipeline with a ForEach-Object loop, you must use the current object variable ($_) to refer to the current object from the pipeline. Change this:
$ous | ForEach { Get-ADUser -Filter * -SearchBase "ou=Example,dc=example,dc=local" -Properties ... }
into this:
$ous | ForEach-Object { Get-ADUser -Filter * -SearchBase $_ -Properties ... }
See about_Automatic_Variables for more information.
I think this was my answer.
$colItems = ForEach ($ou in $ous) { Get-ADUser -Filter * -SearchBase $ou -Properties whenCreated | select -Property Enabled,Name,SamAccountName,whenCreated }

powershell output of ad-user pwdLastSet and LastLoginTimeStamp

I'm working on a script that will run down a csv of LastName and FirstName of users on a domain and return someinfo about them in another csv.
Returning the properties is not an issue, but when I try to convert pwdLastSet and LastLogonTimeStamp to a readable format, it crashes when writing to the csv.
Here is my code. in this example, pwdLastSet will result in an unreadable 64bit number.
$names = import-csv C:\Users\me\Desktop\input.csv
$users = #()
foreach ($name in $names){
$filter = "givenName -like ""*$($name.FirstName)*"" -and sn -like ""$($name.LastName)"""
$users += get-aduser -filter $filter -Properties * | select-object employeeID, sn, givenName, distinguishedName, whencreated, passwordnotrequired, enabled, admincount, pwdlastset
}
$users | select employeeID, sn, givenName, distinguishedName, whencreated, passwordnotrequired, enabled, admincount, pwdlastset | export-csv c:\users\me\desktop\results.csv -NoTypeInformation
I'd like to throw $([datetime]::FromFileTime($user.pwdLastSet)) so it's readable in the output.
Any ideas?
You can use a calculated property to replace the value of a property or create an additional property:
$users += Get-ADUser -Filter $filter -Properties * |
select employeeID, ..., admincount,
#{n='pwdLastSet';e={[DateTime]::FromFileTime($_.pwdLastSet)}}
In this case it's an unnecessary step, though, because Get-ADUser already did that for you and placed that value in the PasswordLastSet property, as #user3815146 already pointed out (+1).
To get an overview of the properties of a user object you can use the Get-Member cmdlet:
Get-ADUser -Filter * -Property * | Get-Member
or list the members of any given user object:
Get-ADUser -Identity 'someuser' -Property * | Format-List *
On a more general note: never append to an array in a loop. The construct
$arr = #()
foreach ($item in $list) {
$arr += Do-StuffWith $item
}
guarantees poor performance, because with each iteration a new array is created (size + 1) and all elements are copied from the old array to the new one. Using a ForEach-Object loop in a pipeline provides far better performance:
$arr = $list | ForEach-Object { Do-StuffWith $_ }
Don't use pwdLastSet, try using PasswordLastSet.
On a different note, have you considered shortening your command to this:
$users += get-aduser -filter $filter -Properties employeeID,sn,givenName,distinguishedName, whencreated,passwordnotrequired,enabled,admincount,passwordlastset