PowerShell to remove all AD attributes when matching the specific string? - azure

I wanted to remove smtp:*#olddomain.com in all of my users, but somehow the cmdlet does not take the wild card to loop through the attributes.
Script:
$DefaultDomain = 'NewCompany.onmicrosoft.com'
$OldDomain = 'olddomain.com'
$DistributionGroups = Import-Csv -LiteralPath C:\Source-DL.csv
$DistributionGroups | ForEach-Object {
Write-Host "Set DL: $($_.DisplayName) into [$($_.Alias+"#"+$DefaultDomain)]" -ForegroundColor Yellow
Set-DistributionGroup -Identity $_.Alias -WindowsEmailAddress $($_.Alias+"#"+$DefaultDomain) -Emailaddresses #{remove="$($_.Alias)#$OldDomain"}
}
The environment is not on-premise AD hence I can only access the Azure AD or Exchange Online cmdlet.

Related

Query ObjectId of ConditionalAccessLocationCondition

I am writing a script to write to Azure, I basically want to find a user, create a network location, create a conditional access policy. This is what I have so far. The trouble is that the $secmon_guid and $location_policy_guid do not work. If I manually put the values in, it works.
# Run these commands first to connect and install without the #
Install-Module -Name AzureAD -AllowClobber -Force # Answer Y to install NuGet. Run once on workstation running script.
Install-Module -Name Microsoft.Graph.Identity.SignIns -Force # Install this to allow us to setup a trusted location. Run once on workstation running script.
Install-Module MSOnline -Force #Allow us to edit users. Run once on workstation running script.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine #Set execution policy to allow our script to do things.
Import-Module -Name AzureAD #The following 3 commands are ran for each client.
Connect-AzureAD # Use GA credentials from Glue
Connect-MsolService #Reauthenticate if necessary.
Get-AzureADMSConditionalAccessPolicy #This will list out all of the existing CA policies. This is a good opportunity to get them into documentation.
Connect-MgGraph #This enabled graph, you will need to approve the request in the popup window.
#Set variable for account name
Set-Variable -name "account" -Value "secmon"
#Create named location for the IP address
$ipRanges = New-Object -TypeName Microsoft.Open.MSGraph.Model.IpRange
$ipRanges.cidrAddress = "IP ADDR"
New-AzureADMSNamedLocationPolicy -OdataType "#microsoft.graph.ipNamedLocation" -DisplayName "Blackpoint IP Address for SecMon" -IsTrusted $true -IpRanges $ipRanges
#Disable MFA for secmon
Get-MsolUser -SearchString "secmon" | Set-MsolUser -StrongAuthenticationRequirements #()
#Get the Azure AD GUID for use later
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select ObjectID
#Name the policy
$name = "Allow Secmon Only from Blackpoint IP"
#Enable the policy. Set to Disabled to test.
$state = "Enabled"
#Get location GUID and save to variable
$location_policy_guid = Get-AzureADMSNamedLocationPolicy | Where-Object -Property DisplayName -Contains 'Blackpoint IP Address for SecMon' | Select-Object -Property Id
#Working on this
#Create the overarching condition set for CA, this is the container.
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
#Include all applications - This might be able to be removed?
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = 'All'
#Create the user condition and include secmon
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeUsers = $secmon_guid
#Add new location policy to CA policy
$conditions.Locations = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessLocationCondition
$conditions.Locations.IncludeLocations = $location_policy_guid
#Grant access control to CA policy
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "block"
#End work
New-AzureADMSConditionalAccessPolicy `
-DisplayName $name `
-State $state `
-Conditions $conditions `
-GrantControls $controls
The error I get is due to poorly formatted GUID's, the values I am pulling are not correct. How can I fix this? Any help is greatly appreciated!
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1054: Invalid location value: #{Id=1234GUID}.
InnerError:
RequestId: 5678GUID
Where you define the variables, you need to use -ExpandProperty on the select-object statement e.g:
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select -ExpandProperty ObjectID
Otherwise, you would have to access your current variable like so:
$conditions.Users.IncludeUsers = $secmon_guid.ObjectID

Can't add device to Azure Active Directory because it has two Object IDs

When I try to add the device looping through a txt file, it says its already a member. When I check the members in the group, nothing changes. From what I've researched, this is due to hybrid setup with on-prem and Azure AD, but I would like to add the devices to the Azure group.
$azgroup = "myGroup"
$machines = get-content ".\deviceList.txt"
write-host "Getting Object ID of group.." -ForegroundColor Green
$objid = (get-azureadgroup -Filter "DisplayName eq '$azgroup'" ).objectid
write-host "Getting group members (We dont want duplicates!).." -ForegroundColor Cyan
$members = Get-AzureADGroupMember -ObjectId $objid -all $true | select displayname
foreach ($machine in $machines) {
$refid = Get-AzureADDevice -Filter "DisplayName eq '$machine'"
$result = ""
$result = ($members -match $machine)
if($result -eq ""){
try{
Write-host "Adding " $refid.displayname -ForegroundColor Cyan
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
}
catch{
write-host "An error occured for " $refid.displayname -ForegroundColor Red
}
}
else
{
write-host $machine " is already a member" -ForegroundColor Green
}
}
I tried treating the specific ObjectID as an array but neither worked to add to Azure AD group
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
If the AzureAD module doesn't work within a hybrid infrastructure, is there any way to bulk add devices to a group in Azure AD?
Here is the working solution. Ok so due to each device having more than one reference IDs, I just treated like an array. This is the part of my code I had to change:
[String]$refid = (Get-AzureADDevice -Filter "DisplayName eq '$machine'")[0].ObjectId
I misplaced the my index ([0]) and placed it after the property, not before it. Then I made sure it outputed a string for good measure, although you can check this with the .gettype() method. Because the on-premise DC and Azure sync, you can use these Device reference IDs interchangeably. It also didnt help outputting a custom error at first, thats what I get for copy-pasting part of someone else's code...

Get device owner from Azure Active Directory group members

Is there a simple way to get the owners of all devices that are assigned to a particular group? I have a Azure AD group that has devices assigned to it and I would like to change all of the assignments from device to user. Is there a way I can find out the owner of the device and assign them as a member in bulk?
You can use the below Powershell Script to get the the device owners of the devices present in the group.
Connect-AzureAD
$Result=#()
$Members = Get-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************"
foreach ($Member in $Members) {
$DeviceOwner = $Member|Get-AzureADDeviceRegisteredOwner
$deviceprops = [ordered] #{
DeviceDisplayName = $Member.DisplayName
DeviceObjectID = $Member.ObjectId
OwnerDisplayName = $DeviceOwner.DisplayName
OwnerUserPrincipalName = $DeviceOwner.UserPrincipalName
OwnerObjectID = $DeviceOwner.ObjectId
}
$deviceobj = new-object -Type PSObject -Property $deviceprops
$Result += $deviceobj
}
$Result
$Result | Export-CSV "C:\DeviceOwners.csv"
I have tested the above on my environment I have only devices present in a group.
Output:
Then to Add owners to the group you can import the csv and add the owners to the Group and then similarly remove the Devices from Group. I tested it only for GetADUser as I don’t want to do the changes in my AAD group.
Code:
$Owners = Import-Csv -Path "C:\DeviceOwners.csv"
#$Owners|Format-Table
Connect-AzureAD
$Owners | ForEach-Object {
#$Owner = $_
#Get-AzureADUser -ObjectId $Owner.OwnerObjectID
$Owner = $_
Add-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************" -RefObjectId $Owner.OwnerObjectID
#$Owner = $_
#Remove-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************" -MemberId $Owner.DeviceObjectID
}
Note :
First Add the Owners to the Group . While running the above script to add Owners to Group keep the Remove command commented . After you have added the Owners to the Group then you can comment the Add command and use the Remove command to remove the Devices from the Group.
Reference:
Install Powersell azuread module :
Command: Install-Module -Name AzureAD
AzureAD Group Module | Microsoft Docs

Recursively list all resource tags within Azure Resource Groups

We have a large number of Azure Subscriptions which currently run into the hundreds.
I'm looking to generate a report (ideally using Azure Powershell or Azure CLI) to recursively extract a list of all tags assigned to every single resource within every resource group, for between 40-50 of the subscriptions.
Currently, I can list all tags assigned at Resource Group level, but I simply can't find a way to list the tags assigned to the individual resources within each Resource Group. The list of subscriptions and resource groups on which I'd like to extract this report, are saved in a CSV file which includes two columns displaying the Subscription name and Resource Group respectively.
Any tips on how to achieve the above would be fantastic and most appreciated.
Not detailed code but the idea here.
1.You should write a loop, in the loop, change the subscription each time by using this cmdlet:
Set-AzContext -Subscription $subscription_name.
2.Then get all the resource group in the specified subscription by using this cmdlet:
$resource_groups = Get-AzResourceGroup
3.Then write a nested loop(loop for each resource group), in this nested loop, use this cmdlet to get all azure resources within a resource group:
foreach($rg in $resource_groups){
$azure_resources = Get-AzResource -ResourceGroupName $rg.ResourceGroupName
}
4.Write another nested loop in step 3, this loop is used to go though all the azure resources within the specified resource group. Then use the code below to fetch tags for each azure resource within the resource group:
foreach($r in $azure_resources){
#the following code can get all the tags for one resource
$r.tags
}
Based on Ivan Yang's logic. I have built the PowerShell Script;
#---------DECLARE VARIABLES------------------------------------#
$bnsSubscription = Get-AzSubscription
$day = Get-Date -Format " ddMMMyyyy"
$tagPath = "C:\mytempfolder\"+"$day-Tag-Details.csv"
$tagFolderPath = "C:\mytempfolder\"
#---------DECLARE VARIABLES------------------------------------#
function Get-ResourceTag {
foreach ($subs in $bnsSubscription) {
Select-AzSubscription -SubscriptionName $subs.Name | Out-Null
Write-Host 'The selected Subscription is' ($subs).Name
New-Item -ItemType file -Path "$tagFolderPath\$($subs.Name).csv" -Force
$resource_groups = Get-AzResourceGroup
$resource_groups_details = Get-AzResourceGroup | Sort-Location ResourceGroupName | Format-Table -GroupBy Location ResourceGroupName,ProvisioningState,Tags
Write-Host 'The selected Resource Group is' ($resource_groups).Name 'and the tag information as follows'
#$resource_groups_details
$resource_groups | Select-Object ResourceGroupName,Tags | Export-CSV -Path "$tagFolderPath\$($subs.Name).csv" -Append
$OutputFile = #()
foreach($rg in $resource_groups){
$azure_resources = Get-AzResource -ResourceGroupName $rg.ResourceGroupName
$TestTags = $Resource.Tags.GetEnumerator()
foreach($r in $azure_resources){
Write-Host 'The selected resource is' ($r).Name 'and the information as follows'
$RGHT = New-Object "System.Collections.Generic.List[System.Object]"
$RGHT.Add("RGName",$r.ResourceGroupName)
$RGHT.Add("ResourceName",$r.name)
$RGHT.Add("Location",$r.Location)
$RGHT.Add("Id",$r.ResourceId)
$RGHT.Add("ResourceType",$r.ResourceType)
$RGHT.Add("ResourceTags",$r.Tags)
$OutputFile += New-Object psobject -Property $RGHT
$OutputFile | Export-Csv -Path "C:\mytempfolder\test22.csv" -append -NoClobber -NoTypeInformation -Encoding UTF8 -Force
}
}
}
}
#---------CALL FUNCTION------------------------------------#
Get-ResourceTag

PowerShell script for returning groups assigned to application

Is there a better way to do this? I want to return the AD groups that are assigned to an Azure AD application. I can find a lot of information on looking at the assigned roles, but not the groups.
The code below, looks at all AD groups first and then ultimately checks the application to see if they are applied. Is there a way to check the application directly?
$ApplicationName = "<NameOfApp>"
$ADGroupList = Get-AzureADGroup -All 1 | Where-Object { $_.DisplayName.Contains('<search string>') } #Find ALL groups that contain search text
#Loop through each group in list and output ObjectID, ResourceDisplayName, and PrincipalDisplayName for each that is assigned to the specified application
ForEach ($group in $ADGroupList){ #Each group in list
Get-AzureADGroupAppRoleAssignment -ObjectId $group.ObjectID | Where-Object { $_.ResourceDisplayName -eq $ApplicationName }
}
The cmdlet for checking a service principal application role assignment is Get-AzureADServiceAppRoleAssignment.
A sample here:
Get-AzureADServiceAppRoleAssignment -ObjectId $applicationObjectId | Where-Object{$_.PrincipalType -eq "Group"}

Resources