AADConnect – Proxy Address in conflict

Had an interesting one recently with a customer that has created cloud accounts for use during COVID-19 with approx 50 users. Each of these accounts were assigned a license and the users used teams, onenote, onedrive etc…. but not exchange online mailbox – as they already have an on-premise mailbox.

After this, we became involved and implemented AADConnect and exchange hybrid.

After removing the exchange license and clearing the mailbox info as per https://techcommunity.microsoft.com/t5/exchange-team-blog/permanently-clear-previous-mailbox-info/ba-p/607619

some users, not all, were not sync’ing correctly in AAD connect.

we can see the objectID that is conflicting

We can then confirm which object it is in O365

and then search for the conflict – which in this case, was a proxy address.


i had previously thought that ProxyAddresses was an exchange related attribute….. and given i had already removed all exchange information from the account… it shouldn’t be there….

At this stage the battle became how to get rid of it – since set-MSOLuser does not seem to allow it.

I found this – https://byronwright.blogspot.com/2017/09/remove-proxy-address-from-office-365.html – but in my instance, the conflicting address is the “correct” address, which keeps getting re-added automatically if you remove it.

Renaming the account temporarily doesn’t work – as the proxy address (as a user account attribute for an unknown reason) seems to update to match the UPN when changed.


This article had a good suggestion – https://www.petenetlive.com/KB/Article/0001588 but resulted in an error

Failed to apply fix – User with conflicting attribute is soft deleted in Azure Active Directory. Ensure the user is hard deleted before retrying.<a href=”https://go.microsoft.com/fwlink/?linkid=2007018″ target=”_blank”>Read More</a>

and we cant hard delete the user – they have data…


So – what are we left with? Hard matching. A process i was aware of, had never had to do (until now) – but thought was going to be overkill for this situation….. but apparently i was wrong.

There is a script here to help – https://gallery.technet.microsoft.com/office/immutableid-hard-match-in-d3518b08 or, if, like me, you prefer to step through it (when there is a small number of affected users)

import-module ActiveDirectory

$user = “SameAccountName” (not UPN)

$guid = [guid]((Get-ADUser -Identity $user).objectGuid)

$immutableId = [System.Convert]::ToBase64String($guid.ToByteArray())

Set-MsolUser -UserPrincipalName <UPN> -ImmutableId <Base64String>


this should work…. but didnt, instead i got the error

Set-MsolUser : Uniqueness violation. Property: SourceAnchor.
At line:1 char:1
+ Set-MsolUser -UserPrincipalName benjamin.primus@rtwsa.com -ImmutableI …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Set-MsolUser], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UniquenessValidationException,Microsoft.Online.Adminis


Then it clicked – this guy must have had an account previously…. run

get-msoluser -all -returndeletedusers

and sure enough – there it was….. with the immutableID assigned to that account…. so i then ran

Get-MsolUser -ReturnDeletedUsers -UserPrincipalName <UPN> | Remove-MsolUser -RemoveFromRecycleBin -Force

Followed by setting the immutableID again – which went through this time.

I then waited for AADConnect to sync again – which went through without error…. “yay” – i thought…. but then the user no longer showed up in the O365 GUI, and powershell showed

Errors : {Microsoft.Online.Administration.ValidationError,

i used https://support.microsoft.com/en-us/help/2741233/you-see-validation-errors-for-users-in-the-office-365-portal-or-in-the

to troubleshoot this, in particular

$errors = (Get-MsolUser -UserPrincipalName “<User_ID>”).Errors

Get-MsolUser -HasErrorsOnly | select DisplayName,UserPrincipalName,@{Name=”Error”;Expression={($_.errors[0].ErrorDetail.objecterrors.errorrecord.ErrorDescription)}} | Export-csv c:\temp\validationerrors.csv

In this users case, there was still something hanging around from an old mailbox

The execution of cmdlet Set-SyncMailUser failed. The value “8dceb397-5af1-4142-8689-24bffeb83f92” of property “ArchiveGuid” is used by another recipient object. Please specify a unique value.


This lead me to https://docs.microsoft.com/en-us/archive/blogs/exovoice/how-to-fix-office365-user-provisioning-issues-that-are-generated-by-faulty-exchange-attributes

Run this to get the conflicting GUID

(Get-MsolUser -UserPrincipalName affecteduser@domain.com).errors.errordetail.objecterrors.errorrecord| fl

Then run this – with the inserted GUID from the above step

Get-Recipient -IncludeSoftDeletedRecipients ‘ExchangeGUID value’|ft RecipientType,PrimarySmtpAddress,*WhenSoftDeleted*

in my case – it was a soft deleted mailbox, so i then run

Remove-MailUser ‘ExchangeGUID value’ -PermanentlyDelete

After this – it was finally all good on next AADConnect Sync.

This whole thing was one huge pain in the arse…. but, at the same time, i learnt a lot…. I’ve previously always setup AADConnect first – and therefore not had cloud accounts that need to be merged etc. The whole process is way fucking harder than it needs to be…. which is very Microsoft…. but, i feel like this will come in useful in future!

Azure AD sync objects not syncing – specifically some room and equipment mailboxes

I have a client who is slowly going to O365 and has asked us to pick up where another consultancy left off.

Some objects were not syncing with O365, even though the OU was included in the AADConnect config.

First issue was easy – the UPN suffix on a number of objects had not been changed, updated that, away they went.

The next issue, took me a while to suss out.

Within the Synchronisation service manager, I could see there was 22 “disconnects”… but no details on what that meant…. took a while, but I found that the issue was caused by the mailboxes which were listed as object type “placeholder”. So…..

Open Synchronisation Service Manager

Go to connectors

Right click on your AD connector and select “Search connector space”

Optionally specify a DN to search

Find objects that have a “object type” of “placeholder”


I tried a number of things to try and get rid of “placeholder” – in the end, it was a simple password reset…. don’t have to enable the account, just set the password to something valid, and then it will sync in AADConnect fine.

Considering the accounts are all disabled, and therefore resetting all the passwords doesn’t matter, I ran the following powershell over the top-level resources OU

Get-ADUser -Filter * -SearchScope Subtree -SearchBase “OU=Resources,OU=Contoso,DC=au” | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “ComplexPassword” -Force)




Scripting Office 365 licensing with disabled services

Have had a few clients request scripts to automatically set assign licenses to users in Office 365 – Generally pretty simple. Recently I had a client ask to disable a particular service within a license – again, not all that difficult – unless you want to actually check if a license/service is already configured and not make any changes. Took a little while to work out, so figured I’d share it with those interested!


Just to set a license for a user is a pretty simple process – all you need is the license ‘SkuId’ value. To get a list of the ones available in your tenant, run: Get-MsolAccountSku. You’ll get a list of the available license SkuId’s and how many are active/consumed. In this article we’ll use an example SkuId of “Contoso:STANDARDWOFFPACK_IW_STUDENT”. Once you have the SkuId, all you need to run to assign the license is:

Set-MsolUser -UserPrincipalName user@contoso.com -UsageLocation AU

Set-MsolUserLicense -UserPrincipalName user@contoso.com -AddLicenses “Contoso:STANDARDWOFFPACK_IW_STUDENT”


Note: in order to assign a license, you also need to first assign a usage location to the user. If that’s already assigned, you can skip that line.


What if you didn’t want to have all the applications available for the user? For example, the above license includes Yammer Education. In this case, we need to create a ‘License Options’ object first.

$LicenseOption = New-MsolLicenseOptions -AccountSkuId “Contoso:STANDARDWOFFPACK_IW_STUDENT” -DisabledPlans YAMMER_EDU

Set-MsolUserLicense -UserPrincipalName user@contoso.com –LicenseOptions $LicenseOption


So where did we get the “YAMMER_EDU” from? You can list the available services for a license by running:

(Get-MsolAccountSku | where {$_.AccountSkuId -eq ‘Contoso:STANDARDWOFFPACK_IW_STUDENT’}).ServiceStatus


What if we wanted to disable multiple services in the License Option? The “-DisabledPlans” option accepts a comma-separated list. For example:

$LicenseOption = New-MsolLicenseOptions -AccountSkuId “Contoso:STANDARDWOFFPACK_IW_STUDENT” -DisabledPlans YAMMER_EDU, SWAY


Ok, so now we know how to get the available licenses and related services – as well as how to assign the license to the user. What if we wanted to check if a license is assigned to a user first? Personally, I’m not a huge fan of just re-stamping settings each time you run a script – so I thought I’d look into it. The easiest method I’ve found is to try bind to the license, then check if it’s $null or not:

$User = Get-MsolUser -UserPrincipalName user@contoso.com

$License = $User.Licenses | Where{$_.AccountSkuId -ieq “Contoso:STANDARDWOFFPACK_IW_STUDENT”}

If ($License) {Write-Host “Found License”} else { Write-Host “Didn’t Find License”}


From there we can do whatever we want – if the license is found and that’s all you care about, you can skip – otherwise you can use the other commands to set the license.

So what if we also want to make sure YAMMER_EDU is disabled as well? That’s a little trickier. First we need to bind to the license like we did above, then we need to check the status of the relevant ‘ServicePlan’.

$User = Get-MsolUser -UserPrincipalName user@contoso.com

$License = $User.Licenses | Where{$_.AccountSkuId -ieq “Contoso:STANDARDWOFFPACK_IW_STUDENT”}



If($License.ServiceStatus | Where{$_.ServicePlan.ServiceName -ieq “YAMMER_EDU” -and $_.ProvisioningStatus -ine “Disabled”})


Write-Host “YAMMER_EDU isn’t disabled”




At this point it’s probably a good idea to talk about the structure of these objects – you may not need to know it, but for anyone trying to modify these commands it might be helpful.

  • A ‘User’ object contains an attribute ‘Licenses’. This attribute is an array – as a user can have multiple licenses assigned.
  • A ‘License’ object contains two attributes relevant to this script; ‘AccountSkuID’ and ‘ServiceStatus’
    • AccountSkuId is the attribute that matches up with the AccountSkuId we’re using above
    • ServiceStatus is another array – it contains an array of objects representing the individual services available in that license – and their status.
  • The two attributes attached to a ‘ServiceStatus’ object that we care about are:
    • ServicePlan.ServiceName – this is the name to match the service above (eg: YAMMER_EDU)
    • ProvisioningStatus – this can be a bunch of values, but mostly ‘Success’, ‘Disabled’ or ‘PendingInput’. I’d assume there’s also ‘Provisioning’, but I’ve never seen it.


With this in mind, we can put together a script like the following – it reads the UPN and AccountSkuID from a CSV file, though you could use whatever source you like and update the script accordingly.


As with the previous scripts, you need the following:


You’ll also need to update the 6 variables at the top of the script (paths, etc).



#Input File

$File = “D:\_Temp\ExchangeOnline\Source.csv”


#Log Variables

$LogFile = “D:\_Temp\ExchangeOnline\SetLicenses_$((Get-Date).ToString(“yyyyMMdd”)).log”

$AuditFile = “D:\_Temp\ExchangeOnline\SetLicenses_Audit.log”



$AdminUser = “admin@contoso.com

$PasswordFile = “D:\_Temp\ExchangeOnline\EO_Password.txt”

$KeyFile = “D:\_Temp\ExchangeOnline\EO_AES.key”


Write-Output “$(Get-Date -format ‘G’) ========Script Started========” | Tee-Object $LogFile -Append


#Build the credentials object

Write-Output “$(Get-Date -format ‘G’) Creating credentials object” | Tee-Object $LogFile -Append

$key = Get-Content $KeyFile

$SecurePassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key

$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUser, $SecurePassword


#Import the MSOnline Module

IMport-Module MSOnline


#Connect to MSOnline

Write-Output “$(Get-Date -format ‘G’) Connecting to MSOnline” | Tee-Object $LogFile -Append

Connect-MsolService -Credential $Creds


#Grab the CSV contents

$CSV = Import-CSV $File

#Go through each entry

Foreach($Line in $CSV)


$samAccountName = $line.samAccountName

$UPN = $Line.UPN

$SKUID = $Line.license


Write-Output “$(Get-Date -format ‘G’) Processing User $UPN” | Tee-Object $LogFile -Append


#Make sure the user exists in MSOnline

If(Get-MsolUser -UserPrincipalName $UPN)


#Found in MSOnline. Put the user account into a variable

Write-Output “$(Get-Date -format ‘G’) – Located in MSOnline” | Tee-Object $LogFile -Append

$User = Get-MsolUser -UserPrincipalName $UPN

#Check the UsageLocation

If($User.UsageLocation -ine “AU”)


Write-Output “$(Get-Date -format ‘G’) – Location not set to AU. Updating…” | Tee-Object $LogFile -Append

#Update it

Set-MsolUser -UserPrincipalName $User.UserPrincipalName -UsageLocation AU

Write-Output “$(Get-Date -format ‘G’) $UPN Location set to AU” | Out-File $AuditFile -Append



#Check if the license is attached to the user

$SetLicense = $false

Write-Output “$(Get-Date -format ‘G’) – Checking for License: $SKUID” | Tee-Object $LogFile -Append

$License = $User.Licenses | Where{$_.AccountSkuId -ieq $SKUID}



#License is attached. Check to make sure that any services to be disabled are actually disabled

Write-Output “$(Get-Date -format ‘G’) – License already attached. Checking if required services are disabled” | Tee-Object $LogFile -Append

If($License.ServiceStatus | Where{$_.ServicePlan.ServiceName -ieq “YAMMER_EDU” -and $_.ProvisioningStatus -ine “Disabled”})


Write-Output “$(Get-Date -format ‘G’) – YAMMER_EDU not disabled.” | Tee-Object $LogFile -Append

$SetLicense = $True



If($SetLicense){Write-Output “$(Get-Date -format ‘G’) – One or more services not disabled. License requires updating.” | Tee-Object $LogFile -Append}




#License is not attached.

Write-Output “$(Get-Date -format ‘G’) – License is not attached. Will be attached.” | Tee-Object $LogFile -Append

$SetLicense = $True





#License is not attached or not configured correctly. Build up the license with required options

$LicenseOption = New-MsolLicenseOptions -AccountSkuId $SKUID -DisabledPlans YAMMER_EDU

#Set the License

Write-Output “$(Get-Date -format ‘G’) – Setting/Updating license” | Tee-Object $LogFile -Append

Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName –LicenseOptions $LicenseOption

Write-Output “$(Get-Date -format ‘G’) $UPN License set/updated for SkuId: $SKUID” | Out-File $AuditFile -Append




Write-Output “$(Get-Date -format ‘G’) – No changes to license required” | Tee-Object $LogFile -Append



# Clear loop variables for the next run

$samAccountName = $Null

$UPN = $Null

$SKUID = $Null

$User = $Null

$License = $Null

$SetLicense = $Null

$LicenseOption = $Null




Write-Output “$(Get-Date -format ‘G’) – Error: User not found in MSOnline” | Tee-Object $LogFile -Append





Write-Output “$(Get-Date -format ‘G’) ========Script Complete========” | Tee-Object $LogFile -Append

Automating Mailbox Regional Settings in Exchange Online

When you migrate (or create) a mailbox in Exchange Online, the first time a user goes to open their mailbox they are prompted to select their Timezone and Language. I recently had a client ask for a more automated method of pre-populating these values, so thought I’d have a look into it.


Of course, there’s no global way to define these settings for users before they get a mailbox, so the settings have to be set once the mailbox has been migrated – this really only leaves the option of a custom powershell script – either something you run after each migration (or creation), or on a periodic schedule.


First, to the settings themselves. As it turns out, you can use the same commands that you’d use in on premise Exchange: Get-MailboxRegionalConfiguration and Set-MailboxRegionalConfiguration – which also means this script could be adapted to be used on premise as well. The two settings we’re concerned with here are “Language” and “TimeZone”. Since the client we’re dealing with here is solely based in Australia, we’re going to be setting all users to a language of “en-AU”. For the TimeZone, Microsoft provide a list of valid values here: https://support.microsoft.com/en-us/kb/2779520


Except that they’re missing two Australian time zones. The actual valid values for Australia are:

  • AUS Central Standard Time – Darwin
  • Cen. Australia Standard Time – Adelaide
  • AUS Eastern Standard Time – Canberra, Melbourne, Sydney
  • E. Australia Standard Time – Brisbane
  • Tasmania Standard Time – Hobart


So with that in mind, we can use the following commands:

Set-MailboxRegionalConfiguration -Language en-AU

Set-MailboxRegionalConfiguration -TimeZone “AUS Eastern Standard Time”


Since we’re talking about a national business with users in different time zones, the time zone value is going to need to change for each user. In order to automate this, we’ll need some source information available that indicates in which state the user is located – ideally, you’re going to be using the ‘Office’ field in the user’s AD account – though obviously you could use any available attribute. The reason I recommend ‘Office’ (or ‘physicalDeliveryOfficeName’) is because it’s synchronised to Office 365 with the user account (and becomes ‘Office’).


Note: You don’t actually need the value in Office 365 – if you’re running the script on premise, you can query your AD directly and ignore the attributes in 365. When I wrote the script I opted to solely use data that was in Office 365 – primarily because I was developing the script remotely and didn’t have direct access to their AD – so if you want to use your local AD instead of values in 365, you’ll need to modify the script!


For this client, the ‘Office’ value for each user is prefixed with the state (ie: SA, NSW, QLD, WA) – so it was relatively simple to use a ‘Switch’ function in Powershell (similar to a ‘Case’ statement in vbscript).


In order to use the script, you need the following:


You’ll also need to update the 5 variables at the top of the script (paths, etc), as well as the Time Zones (and criteria) in the Switch statement.


#Log Variables

$LogFile = “D:\Scripts\ExchangeOnline\RegionalConfig_$((Get-Date).ToString(“yyyyMMdd”)).log”

$AuditFile = “D:\Scripts\ExchangeOnline\RegionalConfigAudit.log”



$AdminUser = “admin@office365domain.com

$PasswordFile = “D:\Scripts\ExchangeOnline\EO_Password.txt”

$KeyFile = “D:\Scripts\ExchangeOnline\EO_AES.key”


Write-Output “$(Get-Date -format ‘G’) ========Script Started========” | Tee-Object $LogFile -Append


#Build the credentials object

Write-Output “$(Get-Date -format ‘G’) Creating credentials object” | Tee-Object $LogFile -Append

$key = Get-Content $KeyFile

$SecurePassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key

$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUser, $SecurePassword


#Import the MSOnline Module

IMport-Module MSOnline


#Connect to MSOnline.

Write-Output “$(Get-Date -format ‘G’) Connecting to MSOnline” | Tee-Object $LogFile -Append

Connect-MsolService -Credential $Creds


#Connect to Exchange Online

Write-Output “$(Get-Date -format ‘G’) Connecting to Exchange Online” | Tee-Object $LogFile -Append

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ `

-Credential $Creds -Authentication Basic -AllowRedirection

Import-PSSession $Session


#Grab a list of User Mailboxes from Exchange Online. Only modify synchronised ones.

Write-Output “$(Get-Date -format ‘G’) Getting User Mailbox List” | Tee-Object $LogFile -Append

$UserMailboxes = Get-Mailbox -Filter {RecipientTypeDetails -eq ‘UserMailbox’ -and IsDirSynced -eq $true} –Resultsize Unlimited


#Keep a count for the summary at the end

$TotalCount = 0

$UpdatedCount = 0

$ErrorCount = 0


#Go through each mailbox

Foreach($Mailbox in $UserMailboxes)


$Updated = $false



#Grab the UPN

$UPN = $Mailbox.UserPrincipalName

Write-Output “$(Get-Date -format ‘G’) Processing Mailbox $UPN” | Tee-Object $LogFile -Append


#Grab the regional Config

$RegionConfig = Get-MailboxRegionalConfiguration $UPN

#From this we need ‘TimeZone’ and ‘Language’.

#Language should be en-AU

#Valid Timezones are:

# AUS Central Standard Time ‘Darwin

# Cen. Australia Standard Time ‘Adelaide

# AUS Eastern Standard Time ‘Canberra, Melbourne, Sydney

# E. Australia Standard Time ‘Brisbane

# Tasmania Standard Time ‘Hobart


#First, do the language – only change if required

If($RegionConfig.Language -ine “en-AU”)


Write-Output “$(Get-Date -format ‘G’) – Updating Language to en-AU” | Tee-Object $LogFile -Append

Set-MailboxRegionalConfiguration -Identity $UPN -Language en-AU

$Updated = $True

#Write to the audit log file

Write-Output “$(Get-Date -format ‘G’) $UPN Language changed to en-AU” | Out-File $AuditFile -Append



#Next, do the Region

#Grab the Office attribute from the MSOnline Object

$MSOlUser = Get-MsolUser -UserPrincipalName $UPN

$Office = $MSOlUser.Office


#The office attribute will begin with either WA, SA, NSW or QLD

Switch -Wildcard ($Office)


“WA*” {$Timezone = “W. Australia Standard Time”}

“SA*” {$Timezone = “Cen. Australia Standard Time”}

“NSW*” {$Timezone = “AUS Eastern Standard Time”}

“QLD*” {$Timezone = “E. Australia Standard Time”}

default {$Timezone = $Null}



If($Timezone -ne $Null)


#Check if the timezone matches

If($RegionConfig.TimeZone -ine $Timezone)


Write-Output “$(Get-Date -format ‘G’) – Updating TimeZone to $TimeZone” | Tee-Object $LogFile -Append

Set-MailboxRegionalConfiguration -Identity $UPN -TimeZone $TimeZone

$Updated = $True

#Write to the audit log file

Write-Output “$(Get-Date -format ‘G’) $UPN TimeZone changed to $TimeZone” | Out-File $AuditFile -Append





Write-Output “$(Get-Date -format ‘G’) – Error: Invalid Timezone/Office value” | Tee-Object $LogFile -Append




If($Updated) {$UpdatedCount++}


#Clear out the variables for the next run

$UPN = $Null

$RegionConfig = $Null

$MSOlUser = $Null

$Office = $Null

$Timezone = $Null




#Write the summary to the log file

Write-Output “$(Get-Date -format ‘G’) ========Summary=======” | Tee-Object $LogFile -Append

Write-Output “$(Get-Date -format ‘G’) Accounts Checked: $TotalCount ” | Tee-Object $LogFile -Append

Write-Output “$(Get-Date -format ‘G’) Accounts Updated: $UpdatedCount ” | Tee-Object $LogFile -Append

Write-Output “$(Get-Date -format ‘G’) Accounts with invalid Office values: $ErrorCount ” | Tee-Object $LogFile -Append


#Remove any remote powershell sessions

Get-PSSession | Remove-PSSession

Using Azure RM Site to Site VPN with a Dynamic IP

By guest writer: Leon Zippel


In the interests of saving a bit of money, I decided to switch my ADSL service from an expensive business connection to a cheap residential connection. In Australia this also means switching from a static IP address to a dynamic IP address. With most web-based services now able to be proxied via Microsoft’s Web Application Proxy (and other services using unique ports), it seemed like everything would be fine with a combination of a Dynamic DNS service and port forwarding. I only run a development environment at home, so if I could save some money without any real impact, all the better!


After I made the switch, I realised that I’d forgotten about my site-to-site VPN between my development environment and Azure Resource Manager (AzureRM). For those familiar with AzureRM and Site to Site VPN, you’ll know that your on premise IP address is configured in a “Local Network Gateway” object. I thought perhaps that you could enter a DNS entry in the IP address field – no such luck.


So I had a look around online to see if anyone else had some easy solution I could poach. While I could find a solution for Azure Classic, the objects are completely different in AzureRM (and the powershell commands are different) – so while it gave me a direction, I couldn’t use the solution as-is. So I had a look at the available AzureRM powershell cmdlets – primarily ‘Get-AzureRmLocalNetworkGateway’ and ‘Set-AzureRmLocalNetworkGateway’.


The problem I came across was that ‘Set’ command really only accepts two parameters – a LocalNetworkGateway object, and AddressPrefix (for your local address spaces). No option to change the Gateway IP. The documentation didn’t give any additional information either.


Based on previous experience with powershell, I had assumed that the LocalNetworkGateway input object would need to refer to an existing object. As a last resort, I decided to try modify it before setting anyway – and it worked! So essentially we can do something like:


$LNG = Get-AzureRmLocalNetworkGateway -ResourceName <LocalNetworkGatewayName> -ResourceGroupName <ResourceGroupName>

$LNG.GatewayIpAddress = <DynamicIP>

Set-AzureRmLocalNetworkGateway -LocalNetworkGateway $LNG -AddressPrefix @('','')


Obviously this is a fair way from an automated solution that can be run on a schedule! In order to put it into a workable solution, the following overall steps need to be taken:


  1. Configure a dynamic DNS service (such as www.noip.com) – this will need to be automatically updated via your router or client software
  2. On the server that will be running the scheduled task, install the Azure Powershell Cmdlets (as per https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/)
  3. Create an administrative account in Azure AD that has administrative access on the subscription (they must be listed in the Azure Classic portal under Settings > Administrators).
    1. It’s important to note that when using the ‘Login-AzureRM –Credentials’ command that the credentials used must be an ‘organisational account’ – you can’t use a Microsoft Live account (even if it’s a subscription administrator).
  4. Use some method of saving credentials for use in Powershell. I prefer to use a key-based encryption so it’s transportable between computers – a guide on doing this can be found here: http://www.adminarsenal.com/admin-arsenal-blog/secure-password-with-powershell-encrypting-credentials-part-2/
  5. Update the following values in the following script:
    1. DynDNS: the external DNS entry that resolves to your dynamic IP
    2. SubscriptionName: the name of your Azure subscription. This can be retrieved using Get-AzureRMSubscription
    3. User: the organisational administrative account
    4. PasswordFile: the file containing the encrypted password
    5. KeyFile: the file containing the encryption key (obviously you want to keep this safe – as it can be used to reverse engineer the password!)
    6. Address Prefixes on line 42.
  6. When running the script via Task Schedule, ensure you also specify the ‘Start In’ directory – otherwise you need to hard code paths in the script.
#Dynamic DNS Entry for your dynamic IP
$DynDNS = "mydynamicdomain.ddns.net"
#Azure subscription name
$SubscriptionName = "Visual Studio Premium with MSDN"

#UPN of a user account with administrative access to the subscription
$User = "azureadmin@mydomain.net"
#Password file
$PasswordFile = ".\AzurePassword.txt"
#Key file to decrypt the password
$KeyFile = ".\AzureAES.key"

Write-Host "Building Credentials"
#Grab the contents of the key
$key = Get-Content $KeyFile
$SecurePassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $key
#Build the credential object
$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

#Get the Current Dynamic IP
[string]$DynIP = ([System.Net.DNS]::GetHostAddresses($DynDNS)).IPAddressToString
Write-Host "Current Dynamic IP:" $DynIP

#Log into the Azure Tenant
Login-AzureRmAccount -Credential $Creds
#Select the subscription
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
#Grab the current LocalNetworkGateway
$LNG = Get-AzureRmLocalNetworkGateway -ResourceName Local_Network_Gateway -ResourceGroupName RG_AU_SE
#Output the IP to view
Write-Host "Current LocalNetworkGateway IP:" $LNG.GatewayIPAddress
Write-Host "Current Dynamic IP:" $DynIP

#Determine if we need to change it
If($DynIP -ne $LNG.GatewayIpAddress)
    Write-Host "Dynamic IP is different to LocalNetworkGateway IP - Updating..."
    #Update the IP in the LNG Object
    $LNG.GatewayIpAddress =$DynIP
    #Update the LNG Object in Azure. AddressPrefix is required.
    Set-AzureRmLocalNetworkGateway -LocalNetworkGateway $LNG -AddressPrefix @('','')
    Write-Host "No changes required"