Select ManagedBy under OU in Powershell? - powershell

I have this Powershell code
$offices = get-qadobject -Type 'organizationalUnit' -SearchRoot 'ou=Test_OU,dc=domain,dc=org'
Foreach($office in $offices)
{
$line = $office | select Name,Description,ManagedBy
$line
}
It is grabbing everything except for ManagedBy which ends up blank. How do I get the email and name of the ManagedBy object? The AD object contains this data.
Note there's some Quest (https://jschofield22.wordpress.com/tag/get-qadobject/) use in here, but it's similar to Get-ADObject.

How about something like:
Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Base,DC=fabrikam,DC=com" -Properties Description |
Select-Object DistinguishedName,
Name,
Description,
ManagedBy,
#{Name="ManagedBy_mail"; Expression={(Get-ADObject $_.ManagedBy -Properties mail).mail}}

Related

Script to pull base64string from AD objects

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()) }}

Trying to extract a list from AD that contains all of my users, in exception to one OU named Disabled Users. How can I exclude this OU from my list?

This is what I have so far:
Get-ADUser -Filter 'Department -like "*"' -Properties * |
Select -Property DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |
Export-CSV "C:\ad-users.csv"
You can use a Where-Object clause to filter on the users OU
# fill in the DistinguishedName of the 'Disabled Users' OU here
$ouToExclude = 'OU=...'
# Get-ADUser by default returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# so you only need to ask for extra properties not already in this list
Get-ADUser -Filter "Department -like '*'" -Properties DisplayName,Title,Department,Office,OfficePhone |
Where-Object { $_.DistinguishedName -notlike "*$ouToExclude" } |
Select-Object DisplayName,GivenName,Surname,Title,Department,Office,OfficePhone |
Export-Csv "C:\ad-users.csv" -NoTypeInformation
I believe you could do it this way using -LDAPFilter, first you need to query the OU to Exclude and get it's DistinguishedName then you can query all users and filter them where their DistinguishedName does not contain the OU to exclude.
NOTE: This assumes there is only 1 OU with Name Disabled Users. If there are more OUs with the same I would recommend you to hardcode the DistinguishedName of the excluded OU in $ouDN.
It's also worth noting that querying all attributes (-Properties *) for all users is highly inefficient, you should always query only the attributes of interest (-Properties attrib1, attrib2, etc).
$properties = #(
'DisplayName'
'GivenName'
'Surname'
'Title'
'Department'
'Office'
'OfficePhone'
)
$ouToExclude = 'Disabled Users'
$ouDN = (Get-ADOrganizationalUnit -LDAPFilter "(Name=$ouToExclude)").DistinguishedName
Get-ADUser -LDAPFilter "(Department=*)" -Properties $properties | & {
process {
if($_.DistinguishedName -notlike "*$ouDN") { $_ }
}
} | Select-Object $properties | Export-Csv "C:\ad-users.csv" -NoTypeInformation

Find AD user information with DisplayName

I have a list of displaynames and I need to get their AD informations.
Get-Content "C:\displaynames.txt" |
foreach {
$givenname,$surname = $_ -split ' '
if (Get-ADUser -Filter "surname -eq '$surname' -and givenname -eq '$givenname'"){
Get-ADUser -Filter { displayName -match $_} -Properties EmailAddress, Manager | Select Givenname, Surname, SamAccountName, EmailAddress, Manager}
else {Get-ADUser -Filter { displayName -like "AD Test"} -Properties EmailAddress, Manager | Select Givenname, Surname, SamAccountName, EmailAddress, Manager}
} | Export-Csv -Path C:\result.csv
This works fine, but only if users have no middle names ex. John Moore
If the user has a middle name, it doesn't pick it up.
How can I change the script so it picks up users with middle names ex. John Roger Moore?
As Mathias R. Jessen already commented, you can use the -Filter on property DisplayName directly.
The Filter should be a string, not a scriptblock.
Using -Filter also has the advantage that you can suppress exceptions being thrown, so I would build in a step to confirm that we indeed did find a user with that displayname:
Get-Content "C:\displaynames.txt" | ForEach-Object {
$user = Get-ADUSer -Filter "DisplayName -eq '$_'" -Properties DisplayName, EmailAddress, Manager -ErrorAction SilentlyContinue
if ($user) {
# output the wanted properties as **object**
$user | Select-Object Givenname, Surname, SamAccountName, EmailAddress, Manager
}
else {
# nobody in this domain with a displayname like that..
Write-Warning "User '$_' could not be found.."
}
} | Export-Csv -Path 'C:\result.csv' -NoTypeInformation
Note that the Manager property is in the form of the managers DistinguishedName. If you want to get other properties for the manager, like his/her name, you will have to use Get-ADUser -Identity $user.Manager to get the wanted property there too
The basic question here is how to account for middle names.
PowerShell 5 has some AI-powered cmdlets.
Here, I will quote an example from the documentation.
Example 2: Simplify format of a string
$composers = #("Johann Sebastian Bach", "Wolfgang Amadeus Mozart", "Frederic Francois Chopin", "Johannes Brahms")
$composers | Convert-String -Example "first middle last=last, first"
Bach, Johann
Mozart, Wolfgang
Chopin, Frederic
Brahms, Johannes
The first command creates an array that contains first, middle and last names. Note that the last entry has no middle name.
The second command formats the names according to the example. It puts the last name first in the output, followed by the first name. All middle names removed; entry without middle name is handled correctly.
Convert-String (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Docs

PowerShell to create a list of AD-users and properties from csv of samAccountNames

I'm trying to create a list of users with other AD properties (Name, sAC, Description) from a file with only samAccountName for each user.
When I try this:
$file=import-csv "C:\newtest.csv"
$file | ForEach-Object {
get-aduser -Identity $_.samAccountName -Properties * | Select-Object Name, samAccountName, Description|Export-Csv C:\newerTest.csv
}
I get an error "Get-ADUser : Cannot validate argument on parameter 'Identity'..."
I've used other Stack Questions to also try building it with -Filter as so:
$file=import-csv "C:\newtest.csv"
ForEach-Object {
Get-ADUser -Filter "samAccountName -like '*$($_samAccountName)*'" -Properties * | Select-Object Name, samAccountName, Description|Export-Csv C:\newerTest.csv
}
but that gives me a "search filter not recognized" error.
TY for any help!
I get an error "Get-ADUser : Cannot validate argument on parameter 'Identity'..."
On the top line of the CSV you have to have "samAccountName" so pick the right column. What happens when you type $file.samAccountName ?
but that gives me a "search filter not recognized" error.
I can not check right now, but it looks like you are missing a "." between $_ and samAccountName. You also were missing "$file |"
$file=import-csv "C:\newtest.csv"
$file | ForEach-Object {
Get-ADUser -Filter "samAccountName -like '*$($_.samAccountName)*'" -Properties * | Select-Object Name, samAccountName, Description|Export-Csv C:\newerTest.csv
}
You can also use your's first variant of code
$file=import-csv C:\newtest.csv
$file | ForEach-Object {
get-aduser -Identity $_.samAccountName -Properties * | Select-Object Name, samAccountName, Description|Export-Csv C:\newerTest.csv
}
But in your file C:\newtest.csv first line must called samAccountName, then in row SAmacc of your users.

Piping AD-User Information to CSV

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
}