How to create a loop for Get-AzureADUserAppRoleAssignment? - azure

I want to make a powershell script that would list me Users list from Azure AD and all Enterprise application assigned to every user from the list.
I have tried to set ForEach-Object loop to iterate each object I would get from Get-AzureADUser
This code works:
$UserId = (Get-AzureADUser -Top 1).ObjectId
Get-AzureADUserAppRoleAssignment -ObjectId $UserId
I 'm trying to loop and iterate for every single output:
$UserId = (Get-AzureADUser).ObjectId | ForEach-Object {
Get-AzureADUserAppRoleAssignment -ObjectId $UserId}
Here is the error message:
Get-AzureADUserAppRoleAssignment : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ObjectId'. Specified method is not supported.
At line:1 char:44
+ Get-AzureADUserAppRoleAssignment -ObjectId $UserID
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzureADUserAppRoleAssignment], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Open.AzureAD16.PowerShell.GetUserAppRoleAssignments

You may create the loop for Get-AzureADUserAppRoleAssignment by these commands below:
$UserId = (Get-AzureADUser).ObjectId
foreach ($eachUserId in $UserId)
{
Get-AzureADUserAppRoleAssignment -ObjectId $eachUserId
}

Related

How to add tags on specific Resourcegroups?

I need to add tags on only the ResourceGroups (which I don't know the name of) where a Keyvault is in. It is possible that there are more than one Keyvaults in several Resourcegroups.
This is how I tried:
Set-AzContext -Subscription $subscriptionID
#Add Currentdate on resourcegroup of Keyvault
$CurrentDate = ((Get-Date).ToString('dd-MM-yyyy'))
$Tags = #{'Date' = $Currentdate}
$Resources = (Get-AzKeyVault).ResourceGroupName
Foreach ($Resource in $Resources){
$ResourcegroupName = (Get-AzKeyVault).ResourceGroupName
$ResourcegroupId = (Get-AzResourceGroup -Name $ResourcegroupName).ResourceId
New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
}
The commands work separately but in this context it gives multiple errors (below error 3 times). Getting the ResourceId gives by what I can see the main error:
Get-AzResourceGroup : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified method is not supported.
At line:11 char:47
+ ... sourcegroupId = (Get-AzResourceGroup -Name $ResourcegroupName).Resour ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzResourceGroup], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceGroupCmdlet
New-AzTag : Cannot validate argument on parameter 'ResourceId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:12 char:27
+ New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-AzTag], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Tags.Tag.NewAzureTagCommand
Thanks a lot for your help!
I understand that you need to add tags on only the ResourceGroups where a Keyvault is in.
I modified a bit your code:
Set-AzContext -Subscription $subscriptionID
#Add Currentdate on resourcegroup of Keyvault
$CurrentDate = ((Get-Date).ToString('dd-MM-yyyy'))
$Tags = #{'Date' = $Currentdate}
$Resources = (Get-AzKeyVault).ResourceGroupName
Foreach ($Resource in $Resources){
$ResourcegroupId = (Get-AzResourceGroup -Name $Resource).ResourceId
New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
}

Error : Get-AzRoleAssignement : Cannot find principal using the specified options

Can some one help to get the details of all users from Azure for their Role assignement with -ExpandPrincipalGroups.
I have tried for one user and it is working fine but when i run the query for all azusers then it gives an error.
Here is the command I am trying:
$user = (Get-AzADUser).UserPrincipalname
Get-AzRoleAssignment -SignInName $user -ExpandPrincipalGroups | Select-Object DisplayName,RoleDefinitionName, Scope
Get-AzRoleAssignment -SignInName $user -ExpandPrincipalGroups | Select-Object DisplayName,RoleDefinitionName, Scope
Get-AzRoleAssignment : Cannot find principal using the specified options
At line:1 char:1
+ Get-AzRoleAssignment -SignInName $user -ExpandPrincipalGroups | Selec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzRoleAssignment], KeyNotFoundException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.GetAzureRoleAssignmentCommand
welcome back suri,
you need to pass the parameter SignInName of the command Get-AzRoleAssignment as string not a list
Get-AzRoleAssignment
-SignInName <String>
-ResourceGroupName <String>
[-RoleDefinitionName <String>]
[-IncludeClassicAdministrators]
[-DefaultProfile <IAzureContextContainer>]
[<CommonParameters>]
so this could be handled as follow
(Get-AzADUser).UserPrincipalname | % { Get-AzRoleAssignment -SignInName $_ | Select-Object DisplayName,RoleDefinitionName,Scope}
DisplayName RoleDefinitionName Scope
----------- ------------------ -----
Mahmoud Moawad Owner /subscriptions/XXXXX-XXXX-XXXXX-XXXX-XXXX
Mahmoud Moawad User Access Administrator /

Enable/Disable availability tests in Azure on Schedule

I'm wondering if there is an easy way to run scheduled automation commands in Azure.
I managed to write Enable/Disable command for availability tests both in
Azure CLI:
az resource update --set properties.enabled=true --name 'someName' --resource-type 'Microsoft.Insights/webtests' --resource-group 'soemResourceGroup'
and
Powershell:
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
problem is that I'm not sure to run them outside of Comamnd line and on schedule. I've read that I could use Automation account to use powershell scripts but that seems a nightmare since I got tons of issues with authentication (not sure why).
Is that an only way ?
EDIT:
I post the errror I was/am getting below.
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Regards.
You could follow the steps as below to use the azure runbook in automation to do that.
1.Navigate to your automation account -> Runbooks -> Create a runbook -> create a Powershell runbook.
2.In the runbook, add the script to login, your complete script should be like below. (Before running the runbook, make sure you have imported the AzureRM.Resources and AzureRM.Profile powershell module in your automation account -> Modules, if not, in the Modules -> Browse Gallery, search for the modules and import them.)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
3.After running the script successfully, follow this link Scheduling a runbook in Azure Automation to add a schedule to your runbook.

Why isn't VScode pwsh terminal able to see my azure resource groups?

I'm trying to tag all my running VMs from azure with tags from a CSV file but my PowerShell script is failing when being run from VSCode PowerShell core terminal.
I double-checked and I have set the correct active subscription (we have multiple tenants and subscriptions), but the output says that it can't find my resource groups (they are there for sure).
Enable-AzureRmAlias
$csv = import-csv "C:\Users\popes\Desktop\Jedox\Powershell scripts\Tagging\Tagging.csv"
$csv | ForEach-Object {
# Retrieve existing tags
$tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM).Tags
# Define new value pairs from CSV
$newTags = #{
company = $_.Company
dns = $_.DNS
type = $_.Type
CN = $_.CN
}
# Add new tags to existing set (overwrite conflicting tag names)
foreach($CN in $newTags.Keys){
$tags[$_] = $newTags[$_]
}
# Update resource with new tag set
Set-AzResource -ResourceGroupName $_.RG -Name $_.VM -Tag $tags -ResourceType "Microsoft.Compute/virtualMachines"
}
The output:
Get-AzResource : Resource group 'machine774_rg' could not be found.
At line:3 char:14
+ ... $tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Mi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzResource], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
Cannot index into a null array.
At line:15 char:9
+ $tags[$_] = $newTags[$_]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Try to use Clear-AzContext, then login with specific tenant and subscription, Connect-AzAccount -Tenant "xxxx-xxxx-xxxx-xxxx" -SubscriptionId "yyyy-yyyy-yyyy-yyyy".

Power Shell: Using variables when trying to add users to group

I have been trying to find a way to bulk add users to a group from a variable.
I create my variables.
Test my variables. And then when I use them, the system interprets them in a way I didn't expect. Has anyone figured out how to best automate this process?
PS C:\WINDOWS\system32> $user = get-MsolUser | Select ObjectID
PS C:\WINDOWS\system32> $user
ObjectId
--------
97232511-7ea5-4f26-9372-************
baa75007-e0fc-4265-b17c-************
PS C:\WINDOWS\system32> $group = get-MsolGroup -ObjectId 776da14a-9c10-4dd1-b880-************ | Select ObjectID
PS C:\WINDOWS\system32> $group
ObjectId
--------
776da14a-9c10-4dd1-b880-************
PS C:\WINDOWS\system32> Add-MsolGroupMember -GroupObjectID $group -GroupMemberType User -GroupMemberObjectId $user
Add-MsolGroupMember : Cannot bind parameter 'GroupObjectId'. Cannot convert the "#{ObjectId=776da14a-9c10-4dd1-b880-d0646d49e926}"
value of type "Selected.Microsoft.Online.Administration.Group" to type "System.Guid".
At line:1 char:36
+ Add-MsolGroupMember -GroupObjectID $group -GroupMemberType User -Grou ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-MsolGroupMember], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Online.Administration.Automation.AddGroupMember
PS C:\WINDOWS\system32>
Try this while selecting a group and then pass it to the Add-MsolGroupMember cmdlet.
$group = get-MsolGroup -ObjectId 776da14a-9c10-4dd1-b880-************ | Select-Object -ExpandProperty ObjectID
Alternative to answer provided.
$group = get-MsolGroup -ObjectId 776da14a-9c10-4dd1-b880-************
$users = get-MsolUser
foreach($user in $users){
Add-MsolGroupMember -GroupObjectID $group.objectId -GroupMemberType User -GroupMemberObjectId $user.objectId
}
Because you're returning multiple users you'll want to foreach them as the cmdlet only accepts one argument for the -GroupMemberObjectId. Also with your current set up getting the group is obsolete since you already know the object id you could achieve the same with.
$groupObjectId = "776da14a-9c10-4dd1-b880-************"
$users = get-MsolUser
foreach($user in $users){
Add-MsolGroupMember -GroupObjectID $groupObjectId -GroupMemberType User -GroupMemberObjectId $user.objectId
}

Resources