create a script for azure pim roles assigned to users - azure-powershell

$filters = "(roleDefinitionId eq '69091246-20e8-4a56-aa4d-066075b2a7a8')" -or "(roleDefinitionId eq '3d762c5a-1b6c-493f-843e-55a3b42923d4')"
Write-Host -Message "Start ......... Script"
$getallPIMadmins = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId "fd799da1-bfc1-4234-a91c-72b3a1cb9e26" -filter $filters
can i use or condition in filter option
if yes how
i am expecting to get output from above condition if use or

I tried to reproduce the same in my environment to get the Azure AD PIM Roles using PowerShell Script
Check this Script to get the azure PIM roles assigned to users.
Note: Uninstall Azure AD module before installing Azure ADPreview
Module and Login with Azure AD Global Admin Credentials. *
Uninstall-Module AzureAD
Install-module AzureADPreview
Connect-AzureAD
Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId 15e217e9-19a5-4006-a9f1-f7e74d8b2a5a
Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId "15e217e9-19a5-4006-a9f1-f7e74d8b2a5a" -Filter "roleDefinitionId eq 'fdd7a751-b60b-444a-984c-02652fe8fa1c'
Result:

Related

Replace email domain for the guest accounts in Azure AD

I am looking to replace email domain (suffix after #) for the guest users in Azure AD via Powershell. As an example, i need to change email address for jdoe from jdoe#abc to #jdoe.xyz
I tried below command but it is not working.
Get-AzureADUser | where {$.UserType -eq 'Guest' -and $.mail -match "#abc.com"} |
ForEach-Object { Set-AzureADUser -ObjectId $($_.ObjectId) -MailNickName "abc#xyz" }
The above might be an incomplete command. Someone suggest what would be the right approach here?
I tried to reproduce the same in my environment to Replace email domain for the guest accounts in Azure AD using Powershell:
To change the email domain for user accounts that have the account type "guest" in Azure Ad using Powershell, you can use below script.
Connect to Azure AD using connect-AzureAd cmdlet.
Use the below cmdlet to retrieve the user accounts the have account type "guest"
Get-AzureAdUser -Filter "accountEnabled eq true and userType eq'Guest'"
Full PowerShell Script
Install-Module AzureAD
Connect-AzureAD
$guestAccounts = Get-AzureAdUser -Filter "accountEnabled eq true and userType eq 'Guest'"
foreach ($guestAccount in $guestAccounts) {
$newUPN = $guestAccount.UserPrincipalName.Replace("#olddomain.com","#newdomain.com")
Set-AzureADUser -ObjectId $guestAccount.ObjectId -UserPrincipalName $newUPN
}
Get-AzureAdUser -Filter "accountEnabled eq true and userType eq 'Guest'"
User UserPrincipal domain changed successfully.

Azure Check Web Application Gateway Already Exists

Using the the Azure Az module is there a way to check if the 'Web Application Gateway' already exists?
I have reproduced in my environment and got expected results as below and I followed Azure Powershell Microsoft-Document:
$result = Get-AzApplicationGateway -Name "XX" -ResourceGroupName "YY" -ErrorAction SilentlyContinue
if($result -eq $null)
{
Write-Host("WAG Does Not Exists")
}else{
Write-Host("WAG Exists")}
XX- Application gateway name,
YY- Name of the resource group
If Application gateway does not exists:
If Application Gateway exists:
You can also use below query and not use if else statements also:
In above you use $? to get if its true or false.
Try to follow above steps you will get expected output as I got.

Assigning group permissions using to Azure DevOps CLI

I am trying to assign permissions to the "build administrators" group using the cli.
The specific permission i want to update is the "Delete Team Project" permission.
The documentation is a little difficult to put together since the information is scattered, specially the parts about security tokens and permissions bits.
I am using the az devops security command. The part i am struggling with is getting the correct token and the setting the correct permission bits
I know the namespace I want to use. it is the environment namespace. Found this out by first checking all the namespaces and finding the guid for the environment namespace.
#get list of all namespaces
az devops security permission namespace list -o table
$envnamespace = <guid from above command for the environment namespace>
# first i set my org and token
$orgUrl = "https://dev.azure.com/<MYORG>"
$personalToken = "<MY_PERSONAL_TOKE>"
$projectName = "<my_project>"
# login using PAT
$personalToken | az devops login --organization $orgUrl
# set default organisation
az devops configure --defaults organization=$orgUrl
# get the group descriptor ID for the group "build administrators"
$id = az devops security group list --project $projectName --output json --query "graphGroups[?displayName == '$groupID'].descriptor | [0]" -o tsv --verbose
# now i want to add permissions for the group "build administrators"
# but i am not sure what the token should be and what permission bits to use
I run the following command to see list the permissions on the group. it returns some tokens but they don't make sense to me. How am i meant to know which token is for what permissions. for example how do i know which token is for "Delete Team Project" permission
az devops security permission list --namespace-id $envnamespace --subject $id
The aim next is to run the following command to update permissions
az devops security permission update --namespace-id $envnamespace --subject $id --token $token2 --allow-bit 4 deny-bit 1 --verbose
The --allow-bit and deny-bit i'm not sure exactly what it should be to set the permission to deny
any advice on the correct way to do this would be appreciated.
how do I know which token is for "Delete Team Project" permission
Run az devops security permission namespace list, the namespaceID of "Delete Team Project" is under the "Project" namespace.
You can get the bit and the namespaceID of the specific Delete Team Project namespace (for reference see screenshot shown below).
How am I meant to know which token is for what permissions
For the tokens, you can refer to Security tokens for permissions management for details, there are listed Token examples for different namespaces.
Another example for your reference (reference jessehouwing's blog) :
az login
az extension add --name "azure-devops"
# Find the group identifier of the group you want to set permissions for
$org = "gdbc2019-westeurope"
# There is a weird edge case here when an Azure DevOps Organization has a Team Project with the same name as the org.
# In that case you must also add a query to filter on the right domain property `?#.domain == '?'`
$subject = az devops security group list `
--org "https://dev.azure.com/$org/" `
--scope organization `
--subject-types vssgp `
--query "graphGroups[?#.principalName == '[$org]\Project Collection Administrators'].descriptor | [0]"
$namespaceId = az devops security permission namespace list `
--org "https://dev.azure.com/$org/" `
--query "[?#.name == 'Git Repositories'].namespaceId | [0]"
$bit = az devops security permission namespace show `
--namespace-id $namespaceId `
--org "https://dev.azure.com/$org/" `
--query "[0].actions[?#.name == 'PullRequestBypassPolicy'].bit | [0]"
az devops security permission update `
--id $namespaceId `
--subject $subject `
--token "repoV2/" `
--allow-bit $bit `
--merge true `
--org https://dev.azure.com/$org/

How to add AD Administrator to Azure SQL Managed Instance with Powershell

I need to add AD administrator to Azure SQL Managed Instances through PowerShell in order to automate deployments.
But it seems there's no way to do it with Azure PowerShell or the REST APIs.
So far I've been trying to set it up like a normal SQL Server.
$sql = Get-AzureRmResource -ResourceGroupName "RSGName" -Name "InstanceName"
-ResourceType "Microsoft.Sql/managedInstances" -ExpandProperties
$dbaId = Get-AzureRmADGroup -DisplayName "ADGroupName" | Select-Object Id
Set-AzureRmSqlServerActiveDirectoryAdministrator -DisplayName "ADGroupName"
-ResourceGroupName "RSGName" -ServerName "InstanceName" -ObjectId $dbaId.Id
But it is giving me errors saying the Server cannot be found on the resource group.

Create AD application with VSTS task

I am trying to create a VSTS task, which should create an AD application.
Taken the DeployAzureResouceGroup as a sample, I have created to following script:
[CmdletBinding()]
param()
Trace-VstsEnteringInvocation $MyInvocation
Import-VstsLocStrings "$PSScriptRoot\Task.json"
$connectedServiceNameSelector = Get-VstsInput -Name "connectedServiceNameSelector" -Require
$connectedServiceName = Get-VstsInput -Name "connectedServiceName"
$connectedServiceNameClassic = Get-VstsInput -Name "connectedServiceNameClassic"
$domains = (Get-VstsInput -Name "domains").Split(";")
$appName = Get-VstsInput -Name "appName"
if($connectedServiceNameSelector -eq "ConnectedServiceNameClassic")
{
$connectedServiceName = $connectedServiceNameClassic
$action = $actionClassic
$resourceGroupName = $cloudService
}
Import-Module $PSScriptRoot\ps_modules\VstsAzureHelpers_
Initialize-Azure
# Import the loc strings.
Import-VstsLocStrings -LiteralPath $PSScriptRoot/Task.json
# Import all the dlls and modules which have cmdlets we need
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Internal.psm1"
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll"
# Load all dependent files for execution
. "$PSScriptRoot\Utility.ps1"
try
{
Validate-AzurePowerShellVersion
$azureUtility = Get-AzureUtility "$connectedServiceName"
Write-Verbose "Loading $azureUtility"
. "$PSScriptRoot\$azureUtility"
Write-Output "test"
Write-Output "Creating a new Application in AAD (App URI -)" -Verbose
$azureAdApplication = New-AzureRmADApplication -DisplayName "test" -IdentifierUris "https://app.com" -HomePage "https://app.com"
$appId = $azureAdApplication.ApplicationId
Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose
Write-Verbose "Completing Azure Resource Group Deployment Task" -Verbose
}
catch
{
Write-TaskSpecificTelemetry "UNKNOWNDEP_Error"
throw
}
When I use a Service principal as Service Endpoint user, I got the error Resource me not found.
When I use my custom AD account, I got the error:Run Login-AzureRmAccount to login.
What am I doing wrong? How can I get this script working?
If you don't need Powershell scripting, go install Azure AD Application Management extension from https://marketplace.visualstudio.com/items?itemName=RalphJansen.Azure-AD-Application-Management
You can add new tasks from pipeline GUI for managing AD applications.
If you do need Powershell scripting, then things get tricky.
Get Powershell code from https://stackoverflow.com/a/51848069/1548275 as a base. The difference is, that if you're not running your code from an extension, you don't have Get-VstsInput nor Get-VstsEndpoint available to execute.
Also, you don't have AzureAD module cmdlets to run. You need to get the Nuget-package, unzip it to your own repo and have it as part of your scripts to be later Import-Module in a pipeline task.
Finally, you need an auth token for Graph API. As the extension code shows, you will need 3 variables:
$tenantId = (Get-AzureRmSubscription).TenantId
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").ApplicationId.Guid
$clientSecret = 'hard-coded, reset SPN password'
As you can see, an extension would have access to all three, but regular script (to my knowledge) doesn't.
SPN password reset is covered in The Net. Briefly, it is something like this:
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").Id.Guid
$password = ConvertTo-SecureString –asplaintext –force "oh, this is very secret!"
New-AzureRmADSpCredential -ObjectId $clientId -Password $password
Also: Update the plaintext password into Azure DevOps project settings, Service Connections for Pipeline to know about the update.