I've got some logic/formatting brain block here.
I have a CSV with GivenName and Surname Property to use
I need to pipe that info against the AD User Estate and Return the information on the users in the list with a few properties including their name, Office, SamAccountName and Email address. I've got as far as this:
$employees = import-csv 'c:\employees\employeelist.csv'
$UserInfo = ForEach ($user in $employees) { Get-ADUser -Filter * | `
Where-Object { $_.GivenName -like
$employee.GivenName -and $_.Surname -like $employee.Surname
}
The information is returned but not in a table form and i can't believe i cant seem to figure how to pipe it to a CSV, it's not working out, it is returned like this:
Reference : 201111
Surname : Smith
GivenName : Name
Effective from : 24-Sep-13
Business Area : Client Ops
Department : ATE
Organisation Unit : ATE Ops
Any Ideas why when i | export-csv i don't get the correct format?
As commented, you are using the wrong variable name in your foreach loop.
($employee should be $user) since that is the variable you define in the loop.
Something like this:
$employees = Import-Csv 'c:\employees\employeelist.csv'
$UserInfo = foreach ($user in $employees) {
Get-ADUser -Filter * -Properties GivenName, Surname, Office, SamAccountName, EmailAddress |
Where-Object { $user.GivenName -eq $_.GivenName -and $user.Surname -eq $_.Surname } |
Select-Object GivenName, Surname, Office, SamAccountName, EmailAddress
}
$UserInfo | Export-Csv -Path 'c:\employees\employees.csv' -NoTypeInformation
As you can see, I'm also naming the properties you want returned, because Get-ADUser by default returns a subset of properties and withour it, you won't get the Office and EmailAddress properties.
Also, I have changed the -like operator into -eq to fetch exact matches.
P.S. Instead of using the Where-Object construction, the code would be more optimized if you use the -Filter like:
$UserInfo = foreach ($user in $employees) {
Get-ADUser -Filter "GivenName -eq '$($user.GivenName)' -and Surname -eq '$($user.Surname)'" -Properties GivenName, Surname, Office, SamAccountName, EmailAddress |
Select-Object GivenName, Surname, Office, SamAccountName, EmailAddress
}
Related
I am working on a powershell script together which will
query an existing OU
select the first and last name, samaccountname, and objectguid, of all users in the OU
Take the objectguid of each user and convert it to a base64string (immutableid)
output the results in a table format with users' first and last name, samaccountname, objectguid, and immutableid, sorted in alphabetical order by users' firstname.
The below script works just fine if I wanted to pull the base64string for one user at a time:
Import-module ActiveDirectory
$UserSamAccount = Read-Host "Provide SamAccountName of a user"
$User = Get-ADuser $UserSamAccount -Properties * | select ObjectGUID
$ImmutableID = [convert]::ToBase64String(([GUID]($User.ObjectGUID)).tobytearray())
Write-Host "ImmutableID for user $UserSamAccount is:" -ForegroundColor Cyan
$ImmutableID
Any help with this will be most appreciated. Thank you in advance!
If I understand correctly your need the following should do the trick. It uses [pscustomobject] to construct your desired output and a ForEach-Object to process each object from the pipeline:
Get-ADUser -Filter * -SearchBase "OU=myOU,DC=myDomain,DC=xyz" -SearchScope OneLevel |
Sort-Object GivenName |
ForEach-Object {
[pscustomobject]#{
GivenName = $_.GivenName
Surname = $_.Surname
SamAccountName = $_.SamAccountName
ObjectGuid = $_.ObjectGuid
ImmutableId = [convert]::ToBase64String($_.ObjectGuid.ToByteArray())
}
} # | Export-Csv path\to\myExport.Csv -NoTypeInformation <= Can pipe this to export later :)
You could also use Select-Object with a calculated property (might be simpler but harder to read):
Get-ADUser -Filter * -SearchBase "OU=myOU,DC=myDomain,DC=xyz" -SearchScope OneLevel |
Sort-Object GivenName |
Select-Object GivenName, Surname, SamAccountName, ObjectGuid, #{ N='ImmutableId'; E={ [convert]::ToBase64String($_.ObjectGuid.ToByteArray()) }}
My goal is to list extended properties of a list of users by Display Name or SamAccountName pulling those names from a Csv. I am using the following script and it works but it either skips names in the Csv or repeats them. If I do one at a time it returns what I need but from the Csv it doesn’t. Csv has one column named Name.
Import-Csv C:\Users\Administrator\Documents\test.txt | Foreach {
Get-ADUser -Filter "DisplayName -eq '$($_.Name)'" -Properties *
} | Select-Object DisplayName, SamAccountName, Title, Department, EmailAddress, ObjectGUID | Sort-Object Displayname | FT
There is nothing wrong with your current code, except for using Import-Csv on a .txt file (test.txt), I would assume this was a typo. I've added an if condition to help you troubleshoot so at least you would know which users where not found.
You should also avoid the use of -Properties *, querying all properties for the users is inefficient and slow.
$properties = #(
'DisplayName'
'SamAccountName'
'Title'
'Department'
'EmailAddress'
'ObjectGUID'
)
Import-Csv C:\Users\Administrator\Documents\test.csv | ForEach-Object {
$adUser = Get-ADUser -Filter "DisplayName -eq '$($_.Name)'" -Properties $properties
if(-not $adUser) {
Write-Warning "'$($_.Name)' could not be found on AD"
return # Go next
}
$adUser
} | Select-Object $properties | Sort-Object Displayname | Format-Table
I have an object called $data. I want to loop through that object to get ADUsers then do some work with that user. The problem I'm having is that the filter is not returning anything. Here is what I have.
foreach($object in $data)
{
$ADuser = Get-ADUser -filter * -Properties * -SearchBase "$($object.ouPath)" |
? { $_.objectGUID -eq $object.GUID -and $_.employeeNumber -eq $object.personID } |
Select-Object employeeNumber,
SamAccountName,
Enabled
try
{}
catch
{}
}
$data contains the following information:
personID : 9408
firstName : John
lastName : Doe
GUID : dde044a6-b11a-4c23-a4c3-7dfe798a98ce
ouPath : OU=test,DC=my,DC=domain
If your query without the conditions in the Where-Object clause works, then there either is no user with that combination of attributes, OR you are mistaking EmployeeNumber with EmployeeID.
Also, getting all users first with all of their properties and filtering out the one user you seek after that is wasteful. Better use the -Filter parameter which gets things done way faster.
Something like:
foreach($object in $data) {
# check if you don't need the EmployeeID attribute instead of EmployeeNumber
$filter = "ObjectGUID -eq '$($object.GUID)' -and EmployeeNumber -eq '$($object.personID)'"
$ADuser = Get-ADUser -Filter $filter -Properties EmployeeNumber -SearchBase $object.ouPath -ErrorAction SilentlyContinue
if ($ADuser) {
# user found, do what needs to be done here. For demo, just output to console
$ADuser | Select-Object EmployeeNumber, SamAccountName, Enabled
}
else {
Write-Warning "Could not find user with ObjectGUID = '$($object.GUID)' and EmployeeNumber = '$($object.personID)'"
}
}
I've been looking online for ways of doing this and I'm at a loss here. I'm looking for a way to look up a particular user within a particular group in AD through powershell. Here's what I've tried.
(Get-ADUser userName –Properties MemberOf).MemberOf
I get a bunch of groups
(Get-ADGroupMember "groupname").name
I get a bunch of usernames
I tried this command but it's taking forever to get results.
(Get-ADGroupMember 'groupname' | Get-ADUser -Property DisplayName | Where-Object { $_.Name -eq 'username'})
Is there a way where I can get a command that both fast and efficient. I'm also looking for their email address and surname and last name.
Thanks in advance
As commented, it is best not use the Name property, but if you have it use the SamAccountName or DistinguishedName of the user you seek to rule out ambiguous names.
$user = Get-ADGroupMember -Identity 'GroupName' |
Where-Object { $_.objectClass -eq 'user' -and $_.SamAccountName -eq 'userSamAccountName' } |
Get-ADUser -Properties DisplayName, EmailAddress, GivenName, Surname # add more properties if you need them
# display the user object on screen
$user
Or do this way:
$user = $null
$member = Get-ADGroupMember -Identity 'TheGroupName' |
Where-Object { $_.objectClass -eq 'user' -and $_.SamAccountName -eq 'TheuserSamAccountName' }
if ($member) {
# add more properties if you need them
$user = Get-ADUser -Identity $member.DistinguishedName -Properties DisplayName, EmailAddress, GivenName, Surname
}
else {
Write-Host "User 'TheuserSamAccountName' is not a member of group 'TheGroupName'"
}
# display the user object on screen
$user
The resulting $user object will also contain these properties:
DistinguishedName, Enabled, Name, ObjectClass, ObjectGUID, SamAccountName, SID, UserPrincipalName
If you don't need all of these properties simply filter them out using
$user | Select-Object DisplayName, EmailAddress, GivenName, Surname
I am attempting to modify the script below so it is showing all Disabled AD user account with Exchange User mailbox still enabled (not Shared Mailbox).
Because the script below also returns Shared Mailboxes which is always created as disabled AD user account.
$Allusers = Get-ADUser -Filter {(enabled -eq $false)} -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName | ?{ $_.homeMDB -ne $null }
$Allusers | Select-Object Givenname, Surname, DisplayName, Mail, MailNickName, SamAccountName, homeMDB | Export-Csv "C:\DisableduserMBX.csv" -NoTypeInformation
It would be good if there is mailbox size as well in the column in MBytes.
Like in the below script:
Get-Mailbox -ResultSize Unlimited |
Get-MailboxStatistics |
Select DisplayName,StorageLimitStatus, `
#{name="TotalItemSize (MB)"; expression={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, `
ItemCount |
Sort "TotalItemSize (MB)" -Descending
To add the MBYTES column, you can try this.
Note this uses the filter as provided by notjustme.
# for the sake of readability..
$filter = '(Enabled -eq $false) -and (msExchRecipientTypeDetails -ne 4) -and ("$null" -ne homeMDB)'
$properties = #('homeMDB', 'mailNickName', 'mail', 'DisplayName', 'SamAccountName', 'Givenname', 'SurName', 'ProxyAddresses')
$Allusers = (Get-ADUser -Filter $filter -Properties $properties |
ForEach-Object {
$size = (Get-MailboxStatistics $_.SamAccountName).TotalItemSize.Value.ToMB()
New-Object -TypeName PSObject -Property #{
homeMDB = $_.homeMDB
mailNickName = $_.mailNickName
mail = $_.mail
ProxyAddresses = $_.ProxyAddresses -join '; '
DisplayName = $_.DisplayName
SamAccountName = $_.SamAccountName
Givenname = $_.Givenname
SurName = $_.SurName
MBytes = $size
}
}) | Sort-Object MBytes -Descending | Export-Csv "C:\DisableduserMBX.csv" -NoTypeInformation
p.s. I've added the ProxyAddresses in there to be able to spot more alias emailaddresses.
p.s. 2 The Identity parameter for Get-MailboxStatistics can be one of:
Name
Display name
Alias
Distinguished name (DN)
Canonical DN
domain name\account name
Email address
GUID
LegacyExchangeDN
SamAccountName
User ID or user principal name (UPN)
msExchRecipientTypeDetails with the value of 4 denotes a shared mailbox. So to exclude these you could try changing your first line of code to the following and see if that gives you the desired output.
$Allusers = Get-ADUser -Filter 'enabled -eq $false -and msExchRecipientTypeDetails -ne 4' -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName | ?{ $_.homeMDB -ne $null }
You should also be able to include the homeMDB-bit in the filter directly;
$Allusers = Get-ADUser -Filter 'enabled -eq $false -and msExchRecipientTypeDetails -ne 4 -and homeMDB -ne "$null"' -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName