Updating Multiple Users ADGroup by EmployeeID - azure

I'm trying to update AzureADGroupMember for multiple users in a CSV File by Employee.
This is what I've got assisted with, but looking to have it update by UPN instead of EmployeeID. This was the successful code that updates ADGroupMember by UPN.
$users = Import-csv "C:\Temp\testgroup2.csv"
$users | ForEach-Object{
Add-AzureADGroupMember -ObjectId 599992-xxxxxxxxxx-699999e9e -
RefObjectId (Get-AzureADUser -ObjectId $_.UPN).ObjectId
}
This is the code where I changed UPN to update by EmployeeID in the CSV.
$users = Import-csv "C:\Temp\testgroup2.csv"
$users | ForEach-Object{
Add-AzureADGroupMember -ObjectId 599992-xxxxxxx-6ee9999e -
RefObjectId (Get-AzureADUser -ObjectId $_.EmployeeID).ObjectId
}
This is the error message I get when trying to update by EmployeeID.
Get-AzureADUser : Error occurred while executing GetUser Code:
Request_ResourceNotFound Message: Resource '18616' does not exist or one
of its queried reference- property objects are not present.
This is what I used to verify that the employee actually has an EmployeeID in Azure.
Get-AzureADUser -ObjectID Xxxxx#hxxxxxx.com | Select-Object *
Any idea why it's reading that the employeeID doesn't exist in Azure even though I've verified?
Thank you,
Update: Adding screenshot of my csv setup, I only have Employee ID in there:
CSV Setup
Update 2: Screenshot of the script I'm running in powershell: Script in PS

The employeeId is not the same with ObjectId, so you could not pass employeeId
to the ObjectId property.
Try the script as below, it works fine on my side.
$users = Import-csv "C:\Users\joyw\Desktop\testgroup.csv"
foreach($user in $users){
$refobjectid = (Get-AzureADUser | Where-Object {$_.ExtensionProperty.employeeId -eq $user.employeeId}).ObjectId
Add-AzureADGroupMember -ObjectId 9d42d3ea-xxxxxxxx-c31428b600ad -RefObjectId $refobjectid
}
My .csv file:
UPN,Role,employeeId
leeliu#xxxxxx.onmicrosoft.com,role1,12345
test#xxxxxx.onmicrosoft.com,role2,123

Related

Add device objects to the Azure group in Powershell foreach

I am trying to run a simple Powershell command let, which is listing all devices matching name criteria and in the next step is moving these devices to a select Azure group.
I tried with:
$result = Get-AzureADDevice -All $True -SearchString "LAP-BK" | ForEach-Object -Process {Add-AzureADGroupMember -ObjectId "25f94620-d850-4ec6-9476-050429d44926" -RefObjectId "$result.ObjectId"}
but that throwing errors. I also tried with
$result = Get-AzureADDevice -All $True -SearchString "LAP-BK" |Select-Object ObjectId
forEach ($item in $result)
{
Add-AzureADGroupMember -ObjectId "25f94620-d850-4ec6-9476-050429d44926" -RefObjectId "$item"
}
exit
The error are various, the last one I get was:
Error occurred while executing AddGroupMember Code: Request_BadRequest Message: Invalid object identifier ' #{ObjectId=debb95af-9h1f-49d6-ad84-8438f9c99b10}'. RequestId: 6df36830-7708-4f6b-b836-cd065f5f60b1
I tried to figure out the error from my end by running your script line by line, and I was able to find exactly where it was occurring:
Referring to Jamesyumnam article, I was able to successfully create and run the below script.
$groupName = "<groupName>"
Connect-AzureAD
$groupObject = Get-AzureADGroup -SearchString $groupName
$outcome = Get-AzureADDevice -SearchString "xxxxxx" | select-object objectID
try{
foreach ($item in $outcome)
{
$deviceObj = Get-AzureADDevice -SearchString $item.DeviceName
Add-AzureADGroupMember -ObjectId $groupObject.ObjectId -RefObjectId $item.ObjectId
}
}
catch {
Write-Host "Device not existed"
}
Executed in Azure PowerShell:
Member added in Azure Portal:
Note: It will be more helpful if you include try{} catch{} blocks in your code to find these kinds of blockers.

How do I check whether a device is already in an Azure group (Powershell)

I'm trying to find a way to see whether an Azure-enrolled device is a member of an Azure group.
The functionality I am aiming for is:
Enter device Object ID
Get all the Azure AD groups
Get the target device using 'Get-AzureADDevice'
Loop through a collection of groups and check if each group contains the device
If the device isn't in a group, add the device to the group. Otherwise skip.
Here is a snippet of my code so far:
$DeviceOID = Read-Host "Enter device's Object ID "
#Get All Azure AD Groups
$AzureGroups = Get-AzureADGroup -All:$true| Sort DisplayName
$Collection = #("Group1", "Group2", "Group3")
$targetDevice = Get-AzureADDevice -ObjectId $DeviceOID
#loop through and add user to each group
foreach ($Item in $Collection)
{
$GroupOID = ($AzureGroups | Where {$_.DisplayName -eq $Item}).ObjectID
$GroupMembers = Get-AzureADGroupMember -ObjectId $GroupOID -All $true
if ($GroupMembers -contains $targetDevice) {
Write-Output "Device already in $Item"
} else {
Add-AzureADGroupMember -ObjectID $GroupOID -RefObjectID $DeviceOID
}
}
The problem I am running into is that although the device is indeed in all 3 groups, the script is not recognising this and is still trying to add the device into said groups:
Add-AzureADGroupMember : Error occurred while executing AddGroupMember
Code: Request_BadRequest
Message: One or more added object references already exist for the following modified properties: 'members'.
I tried to reproduce the same in my environment its work successfully.
When I tried to use your cmdlet, my device is added in azure group successfully as below.
I tried to check whether my device is already exists in azure group I am getting the same error as below.
To resolve this issue, try to remove sort display the term 'Sort' is not recognized as a name of a cmdlet, and I agree with the guiwhatsthat you need to add ($Group in Members.ObjectId -contains $targetDevice.ObjectId) in if statement as below.
$DeviceOID = Read-Host "Enter device's Object ID "
#Get All Azure AD Groups
$AzureGroups = Get-AzureADGroup -All:$true
$Collection = #("Group1", "Group2", "TestGroup")
$targetDevice = Get-AzureADDevice -ObjectId $DeviceOID
#loop through and add user to each group
foreach ($Item in $Collection)
{
$GroupOID = ($AzureGroups | Where {$_.DisplayName -eq $Item}).ObjectID
$GroupMembers = Get-AzureADGroupMember -ObjectId $GroupOID -All $true
if ($GroupMembers.ObjectId -contains $targetDevice.ObjectId) {
Write-Output "Device already in $Item"
} else {
Add-AzureADGroupMember -ObjectID $GroupOID -RefObjectID $DeviceOID
}
}
Output:

How to check which Azure Active Directory Groups I am currently in?

It is possible to return a list that shows all the Azure AD groups the current account is belonging to?
Both using Azure portal web UI and PowerShell are appreciated!
Here's a few different ways other than using the Portal
Azure AD PowerShell Module
Get-AzureADUserMembership
$user = "user#domain.com"
Connect-AzureAD
Get-AzureADUserMembership -ObjectId $user | Select DisplayName, ObjectId
Microsoft Graph PowerShell Module
Get-MgUserMemberOf
$user = "user#domain.com"
Connect-MgGraph
(Get-MgUserMemberOf -UserId $user).AdditionalProperties | Where-Object {$_."#odata.type" -ne "#microsoft.graph.directoryRole"} | ForEach-Object {$_.displayName}
Microsoft Graph API HTTP Request through PowerShell
List memberOf
$user = "user#domain.com"
$params = #{
Headers = #{ Authorization = "Bearer $access_token" }
Uri = "https://graph.microsoft.com/v1.0/users/$user/memberOf"
Method = "GET"
}
$result = Invoke-RestMethod #params
$result.Value | Where-Object {$_."#odata.type" -ne "#microsoft.graph.directoryRole"} | Select DisplayName, Id
Microsoft Graph Explorer
GET https://graph.microsoft.com/v1.0/users/user#domain.com/memberOf
For Portal, simply click on the user for which you want to find this detail and then click on "Groups" button.
If you want to use PowerShell, the Cmdlet you would want to use is Get-AzureADUserMembership.

Azure Activity Log

I want to monitor who made a change in rbac assignment, I created powershell script for collection data from Azure Activity Log. I used below piece of code. Using this solution I am able to get items like:
caller - user who made a role assignment change,
timestamp,
Resource name - on this resource assignment change has been provided,
action type - write or delete
In Activity Log panel in Azure portal, in Summary portal (Message: shared with "user info"), I can see name of a user who has been granted permissions/assignment to the resource, but using my powershell script I am not able to catch this information, is there any method to get this info?
Get-AzureRmLog -StartTime (Get-Date).AddDays(-7) |
Where-Object {$_.Authorization.Action -like
'Microsoft.Authorization/roleAssignments/*'} |
Select-Object #{N="Caller";E={$_.Caller}},
#{N="Resource";E={$_.Authorization.Scope}},
#{N="Action";E={Split-Path $_.Authorization.action -leaf}},
EventTimestamp
script output:
Caller : username#xxx.com
Resource :/subscriptions/xxxx/resourceGroups/Powershell/providers/Microsoft.Compute/virtualMachines/xx/providers/Microsoft.Authorization/roleAssignments/xxxx
Action : write
EventTimestamp : 8/29/2019 10:12:31 AM
Your requirement of fetching the user name to whom the RBAC role is assigned is currently not supported using Az PowerShell cmdlet Get-AzLog or Get-AzureRmLog.
However, we can accomplish your requirement by leveraging Azure REST API for Activity Logs - List and Az PowerShell cmdlet Get-AzureADUser.
In this way as we are depending on Azure REST API for Activity Logs - List (but looks like you want PowerShell way of accomplishing the requirement) so call the REST API in PowerShell as something shown below.
$request = "https://management.azure.com/subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&`$filter={$filter}"
$auth = "eyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$authHeader = #{
'Content-Type'='application/json'
'Accept'='application/json'
'Authorization'= "Bearer $auth"
}
$Output = Invoke-RestMethod -Uri $request -Headers $authHeader -Method GET -Body $Body
$ActivityLogsFinalOutput = $Output.Value
Develop your PowerShell code to get "PrincipalId" (which is under "properties") from the output of your Azure REST API for Activity Logs - List call. The fetched "PrincipalId" is the ObjectID of the user whom you want to get ultimately.
Now leverage Az PowerShell cmdlet Get-AzureADUser and have your command something like shown below.
(Get-AzureADUser -ObjectID "<PrincipalID>").DisplayName
Hope this helps!! Cheers!!
UPDATE:
Please find PowerShell way of fetching auth token (i.e., $auth) that needs to be used in above REST API call.
$ClientID = "<ClientID>" #ApplicationID
$ClientSecret = "<ClientSecret>" #key from Application
$tennantid = "<TennantID>"
$TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $tennantid
$ARMResource = "https://management.core.windows.net/";
$Body1 = #{
'resource'= $ARMResource
'client_id' = $ClientID
'grant_type' = 'client_credentials'
'client_secret' = $ClientSecret
}
$params = #{
ContentType = 'application/x-www-form-urlencoded'
Headers = #{'accept'='application/json'}
Body = $Body1
Method = 'Post'
URI = $TokenEndpoint
}
$token = Invoke-RestMethod #params
$token | select access_token, #{L='Expires';E={[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.expires_on))}} | fl *
I see this new way as well but I didn't get chance to test this out. If interested, you may alternatively try this or go with above approach.
UPDATE2:
$ActivityLogsFinalOutput| %{
if(($_.properties.responseBody) -like "*principalId*"){
$SplittedPrincipalID = $_.properties.responseBody -split "PrincipalID"
$SplittedComma = $SplittedPrincipalID[1] -split ","
$SplittedDoubleQuote = $SplittedComma[0] -split "`""
$PrincipalID = $SplittedDoubleQuote[2]
#Continue code for getting Azure AD User using above fetched $PrincipalID
#...
#...
}
}
Does this work for you?
Get-AzureRmLog -StartTime (Get-Date).AddDays(-7) |
Where-Object {$_.Authorization.Action -like 'Microsoft.Authorization/roleAssignments/*'} |
Select-Object #{N="Caller";E={$_.Caller}},
#{N="Resource";E={$_.Authorization.Scope}},
#{N="Action";E={Split-Path $_.Authorization.action -leaf}},
#{N="Name";E={$_.Claims.Content.name}},
EventTimestamp
My output:
Caller : username#domain.com
Resource : /subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Authorization/roleAssignments/xxxx
Action : write
Name : John Doe
EventTimestamp : 30.08.2019 12.05.52
NB: I used Get-AzLog. Not sure if there is any difference between Get-AzLog and Get-AzureRmLog.
Fairly certain this wouldn't be exposed with this cmdlet. I dont even see this information in the Role Assignments. So not sure what do you mean exactly.

Multiple values fetched when try to get the azure web app objectid

I am trying to get web app objectid using powershell but multiple objectid fetched in the result.
$app = Get-AzureADServicePrincipal -SearchString "devt002"
$app.ObjectId
Result :
33b7cfc5-ca71-412a-ac3b-8b0ca49fb8a6
976a5114-4fab-4b5a-ab92-7403ef25ac29
The original objectid is '976a5114-4fab-4b5a-ab92-7403ef25ac29'.
This is nothing strange, as mentioned in the comment, you have two service principals match the search.
If you want to get the service principal named devt002, try the command below.
$app = Get-AzureADServicePrincipal -SearchString "devt002" | Where-Object {$_.DisplayName -eq "devt002"}
$app.ObjectId
Update:
Try the command as below, the $objectid is what you want.
$webapp = Get-AzWebApp -ResourceGroupName "<resource group name >" -Name "<web app name>"
$objectid = $webapp.Identity.PrincipalId

Resources