AzureAD Powershell Script to Bulk Change Manager Field - powershell

My goal would be to have a Powershell script that can import a CSV to bulk change a users manager field in AzureAD. The CSV would have 2 columns, one with the user and the other with their manager.
I've found scripts to export all users from AzureAD into a CSV, but this doesn't contain a column header for the manager field. I found an AzureAD script than can change the manager field using objectID but that's cumbersome, so ideally I could use an email address for the manager field.
I don't have code to show really, these were pretty basic scripts I found but I'm at best a non Powershell user.

Let us assume that you have below file :
In the left you have the username of the user and on the right you have the username of the new manager.
You could use the below snippet
#connecting to the Azure AD
Connect-AzureAD
#importing the CSV source which has the changes
$data = Import-Csv D:\Temp\Book1.csv
#Iterating through each row in the CSV
foreach ($row in $data)
{
#INFO in the Console
Write-Host "Updating the user :" $row.'User Username' " manager to " $row.'Manager Username' -ForegroundColor Yellow
#Updating the Manager
Set-AzureADUserManager -ObjectId (Get-AzureADUser -ObjectId $row.'User Username').Objectid -RefObjectId (Get-AzureADUser -ObjectId $row.'Manager Username').Objectid
#Completion info in the console for the specified row
Write-Host "Updated." -ForegroundColor Green
}
Explanation :
Step 1 :
Connecting to the Azure AD
Step 2:
Importing the CSV data that needs to be bulk updated
Step 3 :
Iterating through each row, updating the manager field using the commandlet Set-AzureADUserManager
Sample output :

Get-AzureADUserManager and Set-AzureADUserManager only accept ObjectID as input, similar to quite a few other AzureAD cmdlets.
You will need to have a multi step approach to achieve the outcome, below are the steps I would take
Get all Azure AD users, e.g. $AllAzureADUser = Get-AzureADUser -All
Use calculated property to populate manager field based on ObjectID of users you iterate through (essentially this is Foreach loop)
$AllAzureADUserWithManager = $AllAzureADUser | select *, #{ Name = "ManagerObjectId"; Expression = { Get-AzureADUserManager $_.ObjectId }}
Now you have all data required in $AllAzureADUserWithManager to make decisions and update the object. If you want to use UPN to update you can just look up the ObjectId based on UPN.
So say you iterating through an object import from CSV which has targetUserUPN and targetManagerUPN as columns:
$TargetUserObjectId = $AllAzureADUserWithManager | Where {$_.UPN -eq $row.targetUserUPN} | select -ExpandProperty ObjectId
$TargetManagerObjectId = $AllAzureADUserWithManager | Where {$_.UPN -eq $row.targetManagerUPN} | select -ExpandProperty ObjectId
Set-AzureADUserManager -ObjectId $TargetUserObjectId -RefObjectId $TargetManagerObjectId
If you need to run this on daily basis consider using a delta and export to csv previous runs and Filter down to only what is required if you have large number of users.

Related

MS Graph API - Group & membership info

I'm trying to pull out a listing of all groups in our Azure Active Directory org along with all the associated members (be them users, groups, contacts, etc).
Since I was unable to locate a method to do this through the various Microsoft portals with a simple export button I began the process of obtaining access to the Microsoft Graph API/SDK via Powershell.
I'm by no means a PowerShell expert as it's not one of my go-to scripts; however, from what I can tell the ability to pull group info in this fashion is fairly limited.
The following is what I've been able to accomplish thus far:
Pull in a list of the groups using Get-MgGroup -All
Use Get-MgGroupMembers to pull back a list of Directory Objects.
This is where I get stuck. From what I've read it looks like a Directory Object by default only returns the ID and the Deleted Date. I'd like to get a display Name for these objects; I can obviously do this by running the appropriate 'Get' cmdlet for the type of directory object (i.e. Get-MgUser); From what I can tell the type of directory object can't be gleaned via PowerShell with out 'trial-and-error'... This seems highly inefficient to simply get a displayName.
Is there a more effective way to determine either the displayName of a Directory Object via a PowerShell cmdlet or at the very least a type so I can write a case statement to run the right cmdlet on the first try?
For the record this is going to be incorporated in to a Powershell Script, the current iteration of which looks like this and sorta works okay... assuming the Id passed in $member.Id belongs to a User type directory object.
Connect-MgGraph
$groups=Get-mgGroup -All
ForEach ($group in $groups){
$members = #{}
$members = Get-MgGroupMember -GroupId $group.Id -All
ForEach ($member in $members){
$user = Get-MgUser $member.Id
Write-Output $object.ODataType
Write-output $group.DisplayName "," $member.Id "," $user.UserType"," $user.DisplayName "," $user.UserPrincipalName "," $user.Mail >> C:scripts\Azure_Groups.txt
}
}
Would appreciate any direction/assistance on this. Thanks in advance!
Not sure why its not returning all the details on the PowerShell query:
This is working fine in MS Graph Explorer with the results showing all the details of the members:
For more details:https://learn.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0&tabs=http#example-1-get-the-direct-membership-in-a-group

Is it possible to use Get-AzureADServicePrincipal and Get-AzureADServiceAppRoleAssignment to remove users access to all azure enterprise apps?

I am trying to automate the removal all enterprise app access for terminated employee's with powershell but can not figure out if its possible to store all of a users app assignments to a variable and then remove them from all app assignments stored in that variable.
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/assign-user-or-group-access-portal
Until now, there is no such cmdlets to directly assign variable to a user for all the apps that are assigned to that user. Rather than that, you can add all the terminated employees(users)to a group and then assign a variable to them for unassigning them from an application. An example of the same is as follows: -
$group = get-azureadgroup -ObjectId
$spo = Get-AzureADServicePrincipal -ObjectId
$assignments = Get-AzureADServiceAppRoleAssignment -ObjectId $spo.ObjectId | Where {$_.PrincipalDisplayName -eq $group.DisplayName}
$assignments | Select *
Remove-AzureADServiceAppRoleAssignment -ObjectId $spo.ObjectId -AppRoleAssignmentId
$assignments[assignment #].ObjectId
Also, find the below links for your reference: -
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/assign-user-or-group-access-portal
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/disable-user-sign-in-portal
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/manage-application-permissions
Thanking you,

Searching AD Groups attached to specified Server

I'm looking to use powershell, specify a server hostname, and have it display all the AD Groups that have access to that server. From there I'll dig into the groups eventually getting the usernames and storing them in a csv file.
So far I have the code to get the DN of the server -
Get-adcomputer HOSTNAME | select DistinguishedName
Along with having the code to get the eventual usernames and store them in a csv -
$groups= GROUPS
$selectgroups=$groups |Get-Adgroup
$selectgroups |get-adgroupmember -Recursive | Select samaccountname |
Export-csv -path C:\Groups\Members.csv -NoTypeInformation
My problem is I can't figure out how to get powershell to query what groups are on the server I specify. Is this possible or will I have to look at another way of doing this?
Thanks.
Not sure you know exactly what you're looking for. There's no way to tell which AD groups have been granted access to a node via AD. The only thing you can do is look on the local node for AD groups, but there's a lot of places you could want/need to look as Frode F. mentioned already. A common theme would be which AD groups have been added to LOCAL groups on the node in question.
You could use WMI or the ADSI adapter for this information. An ADSI example to get all members of the 'Administrators' local group for server 'NODE123':
$server = "NODE123"
$arrGroupMembers=#()
$Group = "Administrators"
$ADSIComputer = [ADSI]("WinNT://" + $server + ",computer")
$ADSIGroup = $ADSIcomputer.psbase.children.find($Group)
$ADSIMembers= $ADSIGroup.psbase.invoke("Members")
foreach ($member in $ADSIMembers) {
$MemberClass = $member.GetType().InvokeMember("Class", 'GetProperty', $Null, $member, $Null)
if ($memberClass -eq "Group") {
$MemberName = $member.GetType().InvokeMember("Name", 'GetProperty', $Null, $member, $Null)
$arrGroupMembers+=$MemberName
}
}
With the array return above, you now have all groups that have access to NODE123 via being added to the local Administrators group. Maybe this example helps you.

PowerShell Script to sync members of distribution group with SharePoint group

Im in a SharePoint environment where:
distribution lists are in use instead of security lists
can not switch to security list
distribution lists are nested
no user profile sync
So to sync my new SharePoint group "something" I was thinking of running a PowerShell script regulary to fetch all the members hierarchically and put them in the SharePoint group, including checks. Unfortunately I cant install the AD add-in so I installed the Quest AD add-in.
update: I noticed that direct syncing took too long. So I have decided to split the solution: the first AD script output all nested distribution groups (Get-QADGroupMember -Indirect -Type 'group'), although this takes as long as getting all users, this feels safer, since probably this doesnt have to been run that much. Then script 2 read the groups and creates a csv file per group, this is certainly not unique, but with tens of thousands of users, this is the safest way. Then script 3 (underneath) reads the csv files with users and update the SharePoint user group. Then script 4 reads again the usergroup and deletes all the one where the date (in notes) is not equal to the most recent date.
<#
.SYNOPSIS
Syncs All Users in AD distribution Group To SharePoint group:
- Adds new Users
- Updates display name, email when changed
- Deleted Users no longer present
#>
# --------------------------------------------------------
# Variables to Change / Set:
# --------------------------------------------------------
$site = "http://abc-def-ghi:7777"
$SPgroup = "MYCOOLSPGROUP"
$ADgroup = "MYADGROUP"
# --------------------------------------------------------
# Add-SSuser : adds a user to Sharepoint Group
# --------------------------------------------------------
function Add-SSUser {
Param( [string]$account,
[string]$displayname,
[string]$email,
[string]$sitecollectionurl,
[string]$group,
[string]$date)
Get-SPWeb -Identity $sitecollectionurl | foreach-object {
$identityClaimWindowsNTAccount = "i:0#.w|$account"
[Microsoft.SharePoint.SPUser] $ssUser =
$_.EnsureUser($identityClaimWindowsNTAccount)
$_.Groups.GetByName($group).AddUser($ssUser)
$_.Groups.GetByName($group).Update()
Set-SPUser -Identity $ssUser -Web $_.Url -Group $group
# Update properties
$ssUser.Email = $email
$ssUser.Name = $displayname
$ssUser.Notes = "[[$date]]"
$ssUser.Update()
#Write-Host $ssUser.Xml
}
}

Detect null object in powershell:

I am working on implementing some user creation in active directory using the built in powershell commandlets, recently I came across this issue. When attempting to read in a data file of users where $_.UID is one of the fields in the file, I do a Get-ADUser with the UID to check if the user already exists in ldap. If I get a null object, then I would like to create the user because this id is not already in ldap otherwise I would like to skip the entry in the datafile. My script as is creates the users the first time through. If I run it a second time on the same data file (users should no longer be null for the UID field) the if condition is still true and the script attempts to create users a second time. I am new to powershell scripting so I must be misunderstanding something. What am I doing wrong? Your help is appreciated!
Function createUsers{
Import-CSV "~\Desktop\inData.csv" | ForEach-Object {
$USER = Get-ADUser -LDAPFilter "(uid=$_.UID)"
if($USER -eq $Null){ #BROKEN DOESN'T DO ANYTHING
#(!$USER) Doesn't work either
Write-Host "Making next user."
.
.
.
}else{
Write-Host "Skipping, user exists!!"
}
}
}
I think that your problem is in your Get-ADUser Query. There is no property called "uid" in Active Directory. This will make $USER always null, and cause it to always want to create a new user.
Try using sAMAccountName instead:
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$_.UID)"
To get a full list of all the properties available to you, I like to execute the following:
Get-ADUser MyUserName -Properties *