POWERSHELL - Output A Section of the Container/OU of AD-User Account's DistinguishedName - powershell

I was voluntold to learn powershell about a week ago, and learned a lot from here.
I was unable to find a method that worked for me so now I am posting my first question.
I am looking to output under the OU column, not the full DistinguishedName, but a piece of it only.
How would I assign specific part of the DistinguishedName to the OU?
Instead of "CN=,OU=,DC=*", I would only want "(Name of OU) under (Name of Parent OU)"
Input
$ADExtProps =
#(
'Enabled',
'SamAccountName',
'OU'
)
Get-ADUser -Filter * -SearchBase $TestOU -Properties $ADExtProps
Format-Table $ADExtProps -AutoSize -Wrap
Output
Enabled SamAccountName OU
------- -------------- --
True testuser04 {}
True testuser05 {}
True testuser01 {}
True testuser02 {}
True testuser03 {}
True testuser06 {}
True testuser07 {}
True testuser08 {}
True testuser09 {}
False testuser10 {}
Thank you!
How would I assign specific part of the DistinguishedName to the OU?
Instead of "CN=,OU=,DC=*", I would only want "(Name of OU) under (Name of Parent OU)"

It could be done with regex extracting the OU name from the user's DistinguishedName however for the sake of not overcomplicating it, you can first query all OUs using Get-ADOrganizationalUnit then those objects already have the OU .Name which you can use to construct your output:
Get-ADOrganizationalUnit -Filter * | ForEach-Object {
$ouName = $_.Name
Get-ADUser -Filter * -SearchBase $_.DistinguishedName -SearchScope OneLevel |
Select-Object Enabled, SamAccountName, #{N='OU'; E={ $ouName }}
}
If you want to extract the OU common name using regex the following should work:
$TestOU = 'OU=someOU,DC=someDomain,DC=com'
$re = [regex] '(?<=OU=).+?(?<!\\)(?=,)'
Get-ADUser -Filter * -SearchBase $TestOU |
Select-Object Enabled, SamAccountName, #{N='OU'; E={ $re.Match($_.DistinguishedName).Value }}

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

Select ManagedBy under OU in 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}}

Export CSV of AD SamAccountNames and Groups for every user in specific OU

I found a similar question here, but it doesn't quite fit my need and I am having trouble tweaking it to do so.
I need to create a .csv file of all users in a specific OU along with what their AD group membership is in the following format:
User, Group (This is a Header)
User1, Group1
User1, Group2
User1, Group3
User2, Group1
User3, Group1
User4, Group1
User4, Group2
I think this script gets me most of the way there:
$Users = Get-ADGroup -SearchBase "OU=OrgUnit1,OU=OrgUnit2,OU=OrgUnit3,DC=XXX,DC=LOCAL" -Filter * `
| Get-ADGroupMember -Recursive `
| ForEach-Object { Get-ADUser $_ –Properties MemberOf | Select SamAccountName, MemberOf; } `
| Sort-Object SamAccountName
| export-csv C:\Messaging\PowerShell\ADUsers\Test1.csv
The problem with this is two fold.
I want to search on OU=OrgUnit1 without having to search on the full distinguished name, because the sub OU's aren't always the same.
The .csv output has the full distinguished name of the AD Group and I need just the Name of the group with no qualifiers
Use Get-ADOrganizationalUnit to get the OU you want to search:
$ou = Get-ADOrganizationalUnit -Filter "Name -eq 'OrgUnit1'"
Get-ADGroup -Filter * -SearchBase $ou | ...
The memberOf property is a list of groups (or rather their distinguished names). To get the output you want you need to unroll and resolve the group names and create new custom objects with the desired properties:
... | ForEach-Object {
$account = $_.SamAccountName
$_.MemberOf | Get-ADGroup | ForEach-Object {
New-Object -Type PSCustomObject -Property #{
SamAccountName = $account
Group = $_.Name
}
}
} | ...
Also, there's no point in assigning pipeline output to a variable ($Users) if at the end of that pipeline you export the output to a file.
Modified code:
$ou = Get-ADOrganizationalUnit -Filter "Name -eq 'OrgUnit1'"
Get-ADGroup -Filter * -SearchBase $ou |
Get-ADGroupMember -Recursive |
ForEach-Object { Get-ADUser $_ -Properties MemberOf; } |
Sort-Object SamAccountName |
ForEach-Object {
$account = $_.SamAccountName
$_.MemberOf | Get-ADGroup | ForEach-Object {
New-Object -Type PSCustomObject -Property #{
SamAccountName = $account
Group = $_.Name
}
}
} | Export-Csv 'C:\Messaging\PowerShell\ADUsers\Test1.csv'
You don't need this much of code to write. User below code in PowerShell to export all AD user.
Something like this:
Import-Module ActiveDirectory
Get-ADUser -Filter * -Properties * | export-csv c:\ADusers.csv
If you have a big AD, that might take a while though.

Extract AD User information via ADSI

How can I get these properties for a user via ADSI LDAP, these are the properties from Get-ADUser, I need the equivalent for ADSI.
Enabled
PasswordNeverExpires
PasswordExpired
Name
SamAccountName
Mail
PasswordLastSet
My objective is to query the entire domain for all users and get these attributes.
I tried with the Get-ADUser cmdlet and it timed out when querying for the users.
Get-ADUser -Filter * -Properties enabled,PasswordNeverExpires,passwordexpired,Name,SamAccountName,mail,passwordla‌​stset -server sc |
where {$_.Enabled -eq "True"} |
where { $_.PasswordNeverExpires -eq $false } |
where { $_.passwordexpired -eq $false } |
Select Name,SamAccountName,mail,
#{l='PasswordExpires';e={$_.passwordlastset+(Get-ADDefa‌​ultDomainPasswordPolicy).MaxPasswordAge}},
#{l='DaystoExpire';e={(New-TimeSpan -Start (get-date) -end ($_.passwordlastset+(Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge)).days}}
The above command works on a couple of users but if I query a large set of users it gives invalid enumeration context.
The properties SamAccountName, Name, and Mail correspond to AD attributes of the same name. PasswordLastSet is derived from the attribute pwdLastSet. The other 3 properties (Enabled, PasswordNeverExpires, and PasswordExpired) are flags in the userAccountControl attribute.
Use an adsisearcher object with an LDAP query to search AD for user objects, then build custom objects with the desired properties:
$ACCOUNTDISABLE = 0x000002
$DONT_EXPIRE_PASSWORD = 0x010000
$PASSWORD_EXPIRED = 0x800000
$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person))"
$searcher.FindAll() | % {
$user = [adsi]$_.Properties.adspath[0]
New-Object -Type PSCustomObject -Property #{
SamAccountName = $user.sAMAccountName[0]
Name = $user.name[0]
Mail = $user.mail[0]
PasswordLastSet = [DateTime]::FromFileTime($_.Properties.pwdlastset[0])
Enabled = -not [bool]($user.userAccountControl[0] -band
$ACCOUNTDISABLE)
PasswordNeverExpires = [bool]($user.userAccountControl[0] -band
$DONT_EXPIRE_PASSWORD)
PasswordExpired = [bool]($user.userAccountControl[0] -band
$PASSWORD_EXPIRED)
}
}
With that said, why do you want to go to all this trouble instead of simply using Get-ADUser to the same end?
Import-Module ActiveDirectory
$attributes = 'SamAccountName', 'Name', 'Mail', 'PasswordLastSet', 'Enabled',
'PasswordNeverExpires', 'PasswordExpired'
Get-ADUser -Filter * -Properties $attributes | select $attributes
You can use Get-Item over the AD:\ Powershell drive, this cmdlet accepts the -properties argument to retrieve the designated list of properties. Using an asterisk causes the cmdlet to retrieve all properties. An example:
get-aduser -filter "sAMAccountName -like '*'" | % { get-item "AD:\$($_.distinguishedName)" -properties enabled,PasswordNeverExpires,passwordexpired,Name,SamAccountName,mail,passwordlastset }
EDIT: For calculated properties, including "Enabled", "Password never expires" etc, Get-ADUser can also accept -properties argument, so the code is just this:
get-aduser -filter "sAMAccountName -like '*'" -properties enabled,PasswordNeverExpires,passwordexpired,Name,SamAccountName,mail,passwordlastset
An asterisk also works fine.