Category Archives: Azure

Creating a Dynamic Group using the Graph API

Azure has a very nice feature called ‘Dynamic Groups‘. We use these in our customer tenants to dynamically generate a group with actual users, excluding Guest accounts (marked with #EXT#).

As I couldn’t find any articles detailing how to create a Dynamic Group through the Graph API, I’m posting this for whoever it helps 🙂

$dynamicGroupProperties = @{
    "description" = "Dynamic Group Created through the Graph API";
    "displayName" = "Dynamic Group Created through the Graph API";
    "groupTypes" = @("DynamicMembership");
    "mailEnabled" = $False;
    "mailNickname" = "testnickname";
    "membershipRule" = "(user.userPrincipalName -notContains `"#EXT#@`") -and (user.userType -ne `"Guest`")";
    "membershipRuleProcessingState" = "On";
    "securityEnabled" = $True

invoke-webrequest -Headers $headerParams -uri "" -Body (ConvertTo-Json $dynamicGroupProperties) -method POST -Verbose

If you’re not yet used to working with the Graph API, read up on how to connect to the Graph API using Powershell.

Powershell Lock Function

A handy Powershell function to lock / unlock using .NET, to prevent concurrent read/writes to files or anything else you like.

function handleThreadLock{
        #register a thread lock
        $script:threadLock = New-Object System.Threading.Mutex($false, $lockName)
        $waited = 0
            try{$lockState = $script:threadLock.WaitOne(1000)}catch{$lockState=$False}
                if($waited -gt $timeOut){
                    Throw "failed to get a thread within $timeOut seconds!"
        #release a thread lock

In your script, call it like this:

    handleThreadLock -setLock
}catch{Throw "Failed to set lock!"}

    add-content -Path "c:\yourfile.txt" -Value "log entry" -ErrorAction Stop
    handleThreadLock -releaseLock

The process cannot access the file ‘C:\Windows\system32\config\systemprofile\AppData\Roaming\Windows Azure Powershell\TokenCache.dat’ because it is being used by another process.

While building some multithreading Azure Runbooks that log into multiple subscriptions simultaneously, I noticed that these multiple concurrent runs often end up on the same Azure Automation Host.

Apparently, these runbooks then don’t run in full isolation, and the following error may occur:

The running command stopped because the preference variable “ErrorActionPreference” or common parameter is set to Stop: The process cannot access the file ‘C:\Windows\system32\config\systemprofile\AppData\Roaming\Windows Azure Powershell\TokenCache.dat’ because it is being used by another process.

AzureProfile.json may also get locked. I resolved this by doing a retry on the Save-AzureRMContext, and using a randomized file name for the azure json profile:

$randomProfileName = [System.IO.Path]::GetRandomFileName()

Save-AzureRmContext -Path .\$randomProfileName -Force -Confirm:$False

And for my full Azure Login code snippet:

$randomProfileName = [System.IO.Path]::GetRandomFileName()
            Write-Output "Logging in to Azure $azureSubscription"
            $res = Login-AzureRmAccount -Credential $azureCreds -SubscriptionId $azureSubscription -TenantId $tenantId -ErrorAction Stop
            Select-AzureRmSubscription -SubscriptionId $azureSubscription -ErrorAction Stop -TenantId $tenantId
            if($res.Context.Subscription.Id -eq $azureSubscription){
                Write-Output "Logged in to Azure subscription $($res.Context.Subscription.Id)"
                Throw "Failed, we were logged in to $($res.Context.Subscription.Id) while trying to log in to $azureSubscription"
            Save-AzureRmContext -Path .\$randomProfileName -Force -Confirm:$False
            if($tries -ge 30){
            #sleep on failed attempts, as the azure token cache gets locked by concurrent jobs
            sleep -s (Get-Random -minimum 1 -maximum 6)

Transferring a domain to Azure (dns and billing)

Lately I’ve been playing with custom domains in Azure, Microsoft has been allowing us to directly purchase domain in Azure for a while now. This leverages GoDaddy’s API, but Microsoft bills you for the domain, consolidating your domains, management and usage nicely in Azure.

The portal only allows you to purchase new domains, so how do you transfer existing domains to Azure DNS?

First you’ll need a transfer code, which you can get from your current DNS provider. Then, execute the following script:

Register-AzureRmResourceProvider -ProviderNamespace Microsoft.DomainRegistration
$ResourceLocation = "Global"
$ResourceName = "MYDOMAINNAME.NL"
$PropertiesObject = @{
'Consent' = @{
'AgreementKeys' = @("DNPA","DNTA");
'AgreedBy' = ''; #ip address you're running this script from
'AgreedAt' = '2017-17-07T08:37:40'; #roughly the current time
'authCode' = 'DOMAIN TRANSFER CODE'; #code by current domain provider
'Privacy' = 'true';
'autoRenew' = 'true';

New-AzureRmResource -ResourceName $ResourceName -Location $ResourceLocation -PropertyObject $PropertiesObject -ResourceGroupName $rgName -ResourceType Microsoft.DomainRegistration/domains -ApiVersion 2015-02-01 -Verbose

It will take a long time to run, but you’ll have a custom domain in Azure that you can now connect to websites and/or manage through AzureDNS.

Note: this only works for domains OLDER than 60 days and can take 5-7 days until the domain is usable in Azure, all domain records will be copied to an Azure DNS zone.

Azure Runbooks and Write-Progress

If you use Azure Runbooks, but develop scripts locally first…you may like to display progress indicators to yourself when handling large amounts of records / data with Write-Progress.

Be sure to parameterise this, because if you use Write-Progress in an Azure Runbook, it will seriously slow your runbook down, increasing the cost, and if there are over 4000 write-progress calls the runbook will hang and crash.

Azure Powershell MFA and Device Commands

As a guy who really likes to script things, I was very happy to read this today:

Firstly, my Powershell scripts / sessions can now be secured using MFA, without having to rewrite my scripts, except those where I built the Credential object with preset credentials….but that’s old anyway.

Secondly, I can now finally manage Registered Devices with the same Module, allowing me to use these commands:

  • Get-MsolDevice
  • Enable-MsolDevice
  • Disable-MsolDevice
  • Remove-MsolDevice

You can use either the owner’s UPN or the device ID with these commands.

Azure Domain Services

Now isn’t this awesome?

Azure finally announces full support for all services that use Domain Controllers, natively! No more building your domain controllers on VM’s in Azure, it’s become an actual service with these (and more) features:

  • Native support (works like a real domain controller) for all protocols (kerberos, ntlm, ldap)
  • Group policies
  • Domain joins for devices
  • Compatible with and linked to Azure AD
  • Priced per hour

If you have your own domain, don’t forget to set up AADConnect with password sync enabled.

And this is a bit inconvenient, but if you’re running on Azure AD only, you’ll have to expire the passwords of all your users first.

But still, a much requested and anticipated feature we can finally start playing with!