Combining & matching output from Get-AzureADUser, Get-AzureADSubscribedSku , Get-AzureADUserManager - azure

Problem & what i have now
The script
comments are in norwegian btw, if they look strange lol
Connect-AzureAD
#variabel
$Users = Get-AzureADUser -All:$true | where-object { $null -ne $_.AssignedLicenses.SkuId } | Sort-Object CompanyName, UserPrincipalName| Select-Object -Property CompanyName, DisplayName, UserPrincipalName, Department, Mobile, TelephoneNumber
#formatting
$userlistTable = $Users | Format-Table
$userlistHTML = $Users | ConvertTo-Html
#outputs
$userlistHTML > out.html # ut som HTML
$userlistTable > out.txt # ut som Tabell i .txt
$userlistTable # ut som Tabell i terminal
My output as it stands right now:
CompanyName DisplayName UserPrincipalName Department Mobile TelephoneNumber
----------- ----------- ----------------- ---------- ------ ---------------
Company inc Usser Name username#website.com Callsenter 12345678 87654321
What i would like. is a table that has all the info in the output of $Users to inclide the users "SkuPartNumber".
The field u get by running the command Get-AzureADSubscribedSku | Select -Property SkuPartNumber
I would also like to get the users "manager", that u get by running Get-AzureADUserManager.
that last command uses the users Object ID to find their manager.
And to be honest, im very lost on how to combine these commands into one table.
its not the end of the world as it is right now. i could of just have multiple tables but having to manually cross reference these takes some time.
Im really not sure why these things are split into different commands to be honest. i get that a license is via 365 and not azure. but it seems a little backwards that i cant see the licenses from the command showing me all the user information. when a user class in powershell DOES infact show the sku ID. its burried within AssignedLicenses from running the command:
Get-AzureADUser | where-object -property UserPrincipalName -eq "emailhere#domain.com" | FL
This will give you among other things, this info:
AssignedLicenses : {class AssignedLicense {
DisabledPlans: System.Collections.Generic.List`1[System.String]
SkuId: 3b555118-da6a-4418-894f-7df1e2096870
}
conclusion
I know this was a long read. and if u made it this far im sorry.
any help with this would be amazing. This might be super easy to do, but im very far from a powershell wiz. thanks again for reading, and any help.

You can add additional properties to selected objects with calculated properties like Select #{label='name';expression={foo}}
$Users = Get-AzureADUser -All:$true
$Users | Where-Object { $_.AssignedLicenses.SkuId } |
Select-Object -Property UserPrincipalName, ## other properties here...
#{l='ManagerUPN';e={($_ | Get-AzureADUserManager).UserPrincipalName}},
#{l='AssignedSKUs';e={$_.AssignedLicenses.SkuId -join ';'}}
UserPrincipalName ManagerUPN AssignedSKUs
----------------- ---------- ------------
user#domain.com manager#domain.com 00000000-0000-0000-0000-000000000000;11111111-1111-1111-1111-111111111111
It can be slow to run Get-AzureADUserManager for every user, but that's how azure stores the relationships.
When you have a lot of users, it can be slightly faster to get the manager users first, then use Get-AzureADUserDirectReport -all $true to expand all the directreports in one call. The Microsoft.Graph.Users module is also a bit more lightweight

Related

Getting Distribution Groups / Owners w/ PowerShell, but removing entries that have a null or empty owner

I have the lovely job of getting a list of Distribution Groups and their owners from Exchange Online. So far this is working great, but I need to fine tune my output to exclude groups that don't have any owners; and groups that have multiple owners (by returning only the first).
So far this has been fairly difficult as this is sort of my first foray into PShell.
Here's my code:
$job = Get-DistributionGroup | select Name,PrimarySmtpAddress, #{n= "ManagedBy"; e={$_.ManagedBy | Select-Object -First 1 | Where-Object {$_.ManagedBy.Count -eq 0} |foreach {(Get-Mailbox $_).PrimarySMTPAddress}}}
Write-Output $job | ConvertTo-Json
Here's an example of my output:
I basically only want a single string address to be returned. So a single owner of a distro group, no nulls, and only the first address in the collections. (Right now they are blank, I'm probably nuking them with my code- but usually they return 4 or so email addresses but I just want the first person)
Thanks!
By collection you mean the ManagedBy property right? If so, try with { ($_.ManagedBy | Select-Object -First 1 | Get-Mailbox).PrimarySMTPAddress } –
Santiago Squarzon
1 hour ago

View groups for every user in Azure AD with powershell

As the title said. im looking for a way to list every user, with the group(s), they are in.
I'm aware of how you could use Get-AzureADGroupMember -ObjectId "groupidhere"
and then the output is all the users in that group. but how would you automate this? is this even possible to do with powershell?
after this ill be using this table to create a table in Hudu. i havent seen anyone do this with groups and users together though, so for all i know its not possible or supposed to be.
So the output i get here from $Users to also show some of the output from $Groups_Name
A table where i have all the info about a user, but also what groups they are in.
| Name | Email | Group |
so the output would be something like this:
DisplayName UserPrincipalName DisplayName
----------- ----------------- -----------
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Name Nameson user#domain.com Group names
Script im working on (i know this is super messy)
# Table of all users
$Users = Get-AzureADUser -All:$true
# Table of all groups
$Groups = Get-AzureADGroup
# ALL users ObjectId
$Users_ObjectId = $Users | Select-Object ObjectId
# ALL Groups ObjectId
$Groups_ObjectId = $Groups | Select-Object ObjectId
#Group names - list
$Groups_Name = $Groups | Select-Object DisplayName
#User names - list
$Users_Name = $Users | Select-Object DisplayName
foreach ($i in $Users ) {
# If
if ($Groups -contains $Users_ObjectId) {
#print a table with desired formatting
#$Users $Groups_Name
}
}
Try using Get-AzureADUserMembership like this:
$users = Get-AzureADUser -All $true
$report = Foreach ($user in $users) {
$groups = $user | Get-AzureADUserMembership
# create output objects with username and groups:
Foreach ($group in $groups) {
[PSCustomObject][ordered]#{
UserDisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
GroupDisplayName = $group.DisplayName
}}}
# print a table with desired formatting
$report | ft
And the report looks like so:
UserDisplayName UserPrincipalName GroupDisplayName
--------------- ----------------- ----------------
John Smith j.smith#domain.com Marketing
John Smith j.smith#domain.com Marketing-VIPs
John Doe j.doe#domain.com Sales
John Doe j.doe#domain.com Management

How can I split AD information in Powershell into a excel document?

I am a Powershell starter. I have been trying to create a script, that makes an Excel file with some AD information including the DistinguishedName. My script looks like this:
$dn = Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" | select DistinguishedName,SamAccountName,name |export-csv C:\temp\test1.csv -Delimiter ";"
An example of what I get (Note: | means new cell in Excel):
CN=Testuser\, Verfluecht,OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
But in order to group the paths in excel, I need it without the CN (CN=Testuser\, Verfluecht,)
So that it would look like this:
OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
How can I do this?
I tried many things such as .substring and replace, but I could not get it done.
Using this link and a calculated property, it should just drop the first part of the distinguishedname and be left with the parts you need.
Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" |
Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name |
Export-Csv C:\temp\test1.csv -Delimiter ";"
On my test environment, I get the output below (without piping it to Export-Csv).
Get-ADUser -Filter * | Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name
DistinguishedName samaccountname name
----------------- -------------- ----
CN=Users,DC=timhaintz,DC=com Administrator Administrator
CN=Users,DC=timhaintz,DC=com Guest Guest
CN=Users,DC=timhaintz,DC=com DefaultAccount DefaultAccount
CN=Users,DC=timhaintz,DC=com krbtgt krbtgt
Thanks, Tim.

How do I add another column to a System.Object using a list in Powershell?

I am making a script to query active directory via powershell and pull all computers that contain a username in the description field, then filter that list with only computers last logged in the past 14 days.
This is what I have so far:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$lastLogon = $queryAD | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
I'd like to add the list generated from $lastLogon to $queryAD, right now $queryAD is returning two columns with headers Name and Description. I need a third header added called Last Logon Date and contain the list in $lastLogon. Please advise.
You could assign the values to an array of objects to make your output cleaner (if this method is providing you the data you want) like so:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$computer_list = #()
foreach($computer in $queryAD) {
$computer_info = New-Object PSObject -Property #{
Name = $computer.Name
Description = $computer.Description
LastLogonDate = $computer | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
}
$computer_list += $computer_info
}
in which case $computer_list will contain all of the info you're gathering in tidy objects.
...but this method seems overcomplicated. Look into this blog entry by Matt Vogt for a better way to query for old machines in AD.

Export AD User Properties to CSV

I want to interrogate the client' AD to see which users are missing property values such as telephone number ahead of User Profile Sync in SharePoint 2013, the script works but now I need to add a little "magic" in order to create my csv file... I have added a comment below to indicate where I think this "magic" should go!
# get Users and groups
#Get the User from AD
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $domain.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
#$search.Filter = "(&(objectCategory=User)(samAccountName=$userName))"
# get a list of the users but not the sp_ service accounts.
$search.Filter = "(&(objectCategory=User) (!(name=SP_*)) )"
$search.SearchScope ="subtree"
# determine the properties we want back
$colPropList = "name", "jobTitle", "telephoneNumber","mail", "department" , "thumbnailPhoto"
foreach ($i in $colPropList){$search.PropertiesToLoad.Add($i)}
$result = $search.FindAll()
if ($result -ne $null)
{
foreach ( $entry in $result )
{
# this works though I might have incorrect names for some of the properties
$user = $entry.Properties;
$user.name
$user.department
$user.jobTitle
$user.telephoneNumber
$user.mail
$user.thumbnailPhoto
*# !!!!!!This is where I need help!!!!!
# as my $user is effectively an object then I should be able to to use it to create a an object with Add-Member
# Do I breaker down the $user properties and create another object with name values ???*
foreach ($o in $user)
{
Add-Member -InputObject $psObject -MemberType NoteProperty -Name $o -Value $o
}
}
$psObject | Export-Csv c:\dev\aduserList.csv -NoTypeInformation
}
I'm not familiar with directorysearcher / adsi, but if you're migrating to SharePoint 2013 I'd guess you also have a computer with PowerShell.
In that case you should use Microsofts ActiveDirectory module (installed on servers and through RSAT for clients) if you have a 2008 DC or 2003 with Active Directory Web Service.
You could also use Quest ADRoles Module.
PowerShell cmdlets are much easier to use for AD administration. You could then shorten down your script to one line(this is the ActiveDirectory module from Microsoft):
Get-ADUser -LDAPFilter "(!(name=SP_*))" -Properties Name, Title, OfficePhone, Mail, Department, thumbnailPhoto | Select-Object Name, Title, OfficePhone, Mail, Department, thumbnailPhoto | Export-Csv c:\dev\aduserList.csv -NoTypeInformation
I'm not sure if the thumbnailphoto part works as I haven't used that attribute before.
Something like this should work:
$search.FindAll() | select -Expand Properties |
select #{n='name';e={$_.name}},
#{n='department';e={$_.department}},
#{n='jobTitle';e={$_.jobtitle}},
#{n='telephoneNumber';e={$_.telephonenumber}},
#{n='mail';e={$_.mail}},
#{n='thumbnailPhoto';e={$_.thumbnailphoto}} |
Export-Csv c:\dev\aduserList.csv -NoTypeInformation
Note that the properties used in the expression section of the calculated property (#{n='name';e={expression}}) must be lowercased:
#{n='thumbnailPhoto';e={$_.thumbnailphoto}}
Using the Get-ADUser cmdlet from the ActiveDirectory module as Frode F. suggested is a more convenient way to get the information you want, but it requires that the AD PowerShell module is installed on the computer where it's used, and that the AD Web Services are installed and running on a DC.

Resources