Automating Backup Assignment of Azure VMs with Azure Policy and Tag

Managing backups for virtual machines (VMs) in the cloud is crucial for ensuring data security and continuity. Manually configuring backups for each VM can be time-consuming and error-prone. Thankfully, Azure Policy provides a powerful way to automate and enforce backup configurations. In this guide, I’ll walk through how to automatically configure Azure VM backups using Azure Policy targeting VMs with a specific tag and backing them up to an existing Recovery Services vault. I’ll also show you how to create and assign the Azure Policy using Terraform, a popular Infrastructure as Code (IaC) tool.

Note: Code given in this blog is only tested in LAB Environment so thoroughly test this before you use in your environment.

What We Will Achieve:

  1. Tag-Based Targeting: Only VMs with a specific tag will be backed up.
  2. Automatic Backup Configuration: VMs will be automatically configured for backup in an existing Recovery Services vault.
  3. Enforcement via Azure Policy: We’ll use Azure Policy to enforce this configuration.
  4. Terraform Automation: We’ll create and assign the Azure Policy using Terraform.

Step 1: Preparing Your Environment

Before diving into the setup, ensure you have the following:

  • Azure Subscription: With the necessary permissions to create and assign policies.
  • Recovery Services Vault: Already created in the same region as the VMs you want to back up.
  • Tagged VMs: The VMs you want to back up should have a specific tag (e.g., BackupPolicy: Yes).
  • Terraform Installed: Make sure you have Terraform installed and configured to work with Azure.

Step 2: Understanding Azure Policy

Azure Policy allows you to enforce organizational standards and assess compliance across your resources. By creating a policy definition, you can ensure that certain configurations, like VM backups, are automatically applied based on specific criteria, such as resource tags.

Step 3: Creating a Custom Policy Definition

Azure Policy definitions are JSON files that describe the policy. For our task, we’ll create a custom policy that:

  • Identifies VMs with a Specific Tag: The policy will target VMs that have a particular tag.
  • Assigns Them to a Backup Policy: It will configure these VMs to be backed up to a specified Recovery Services vault.

Here’s a sample JSON for the policy definition:

{
  "properties": {
    "displayName": "Configure backup on VMs with a specific tag to a Recovery Services vault",
    "policyType": "Custom",
    "mode": "All",
    "parameters": {
      "tagName": {
        "type": "String",
        "metadata": {
          "description": "The name of the tag that the policy will look for.",
          "displayName": "Tag Name",
          "defaultValue": "BackupPolicy"
        }
      },
      "tagValue": {
        "type": "String",
        "metadata": {
          "description": "The value of the tag that the policy will look for.",
          "displayName": "Tag Value",
          "defaultValue": "Yes"
        }
      },
      "vaultName": {
        "type": "String",
        "metadata": {
          "description": "The name of the Recovery Services vault to back up the VMs to.",
          "displayName": "Recovery Services Vault Name"
        }
      },
      "backupPolicyName": {
        "type": "String",
        "metadata": {
          "description": "The name of the backup policy to apply.",
          "displayName": "Backup Policy Name"
        }
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Compute/virtualMachines"
          },
          {
            "field": "[concat('tags[', parameters('tagName'), ']')]",
            "equals": "[parameters('tagValue')]"
          }
        ]
      },
      "then": {
        "effect": "DeployIfNotExists",
        "details": {
          "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems/properties.friendlyName",
                "equals": "[field('name')]"
              },
              {
                "field": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems/properties.policyName",
                "equals": "[parameters('backupPolicyName')]"
              }
            ]
          },
          "roleDefinitionIds": [
            "/providers/microsoft.authorization/roleDefinitions/aaf6465c-3d9a-4d1a-bb4a-2b3d7e18b503"
          ],
          "deployment": {
            "properties": {
              "mode": "Incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "resources": [
                  {
                    "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
                    "apiVersion": "2019-06-15",
                    "name": "[concat(parameters('vaultName'), '/Azure/protectionContainers/vmworkload/iaasvmcontainerv2/', field('name'))]",
                    "properties": {
                      "protectedItemType": "Microsoft.Compute/virtualMachines",
                      "policyId": "[parameters('backupPolicyName')]"
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
  }
}

Step 4: Implementing Azure Policy with Terraform

Now, let’s automate the creation and assignment of this Azure Policy using Terraform.

Step 4.1: Creating the Terraform Configuration

Create a Terraform file (main.tf) with the following configuration:

provider "azurerm" {
  features {}
}

resource "azurerm_policy_definition" "vm_backup_policy" {
  name         = "vm-backup-policy"
  policy_type  = "Custom"
  mode         = "All"
  display_name = "Configure backup on VMs with a specific tag to a Recovery Services vault"
  description  = "This policy configures VMs with a specific tag to be backed up to a specified Recovery Services vault."

  policy_rule = <<POLICY_RULE
{
  "if": {
    "allOf": [
      {
        "field": "type",
        "equals": "Microsoft.Compute/virtualMachines"
      },
      {
        "field": "[concat('tags[', parameters('tagName'), ']')]",
        "equals": "[parameters('tagValue')]"
      }
    ]
  },
  "then": {
    "effect": "DeployIfNotExists",
    "details": {
      "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
      "existenceCondition": {
        "allOf": [
          {
            "field": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems/properties.friendlyName",
            "equals": "[field('name')]"
          },
          {
            "field": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems/properties.policyName",
            "equals": "[parameters('backupPolicyName')]"
          }
        ]
      },
      "roleDefinitionIds": [
        "/providers/microsoft.authorization/roleDefinitions/aaf6465c-3d9a-4d1a-bb4a-2b3d7e18b503"
      ],
      "deployment": {
        "properties": {
          "mode": "Incremental",
          "template": {
            "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
            "contentVersion": "1.0.0.0",
            "resources": [
              {
                "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
                "apiVersion": "2019-06-15",
                "name": "[concat(parameters('vaultName'), '/Azure/protectionContainers/vmworkload/iaasvmcontainerv2/', field('name'))]",
                "properties": {
                  "protectedItemType": "Microsoft.Compute/virtualMachines",
                  "policyId": "[parameters('backupPolicyName')]"
                }
              }
            ]
          }
        }
      }
    }
  }
}
POLICY_RULE

  parameters = <<PARAMETERS
{
  "tagName": {
    "type": "String",
    "metadata": {
      "description": "The name of the tag that the policy will look for.",
      "displayName": "Tag Name",
      "defaultValue": "BackupPolicy"
    }
  },
  "tagValue": {
    "type": "String",
    "metadata": {
      "description": "The value of the tag that the policy will look for.",
      "displayName": "Tag Value",
      "defaultValue": "Yes"
    }
  },
  "vaultName": {
    "type": "String",
    "metadata": {
      "description": "The name of the Recovery Services vault to back up the VMs to.",
      "displayName": "Recovery Services Vault Name"
    }
  },
  "backupPolicyName": {
    "type": "String",
    "metadata": {
      "description": "The name of the backup policy to apply.",
      "displayName":

 "Backup Policy Name"
    }
  }
}
PARAMETERS
}

resource "azurerm_policy_assignment" "vm_backup_assignment" {
  name         = "assign-vm-backup-policy"
  policy_definition_id = azurerm_policy_definition.vm_backup_policy.id
  scope        = data.azurerm_subscription.primary.id

  parameters = {
    tagName          = "BackupPolicy"
    tagValue         = "Yes"
    vaultName        = "YourRecoveryServicesVaultName"
    backupPolicyName = "YourBackupPolicyName"
  }
}

Step 4.2: Deploying the Terraform Configuration

  1. Initialize Terraform: In the directory where you created the main.tf file, run the following command to initialize Terraform:
   terraform init
  1. Apply the Configuration: Run the following command to deploy the policy and assignment:
   terraform apply

Terraform will prompt you to confirm the changes. Type yes to proceed.

This will create the custom Azure Policy and assign it to your Azure subscription, automatically configuring backups for any VMs with the specified tag.

Step 5: Monitoring and Compliance

After assigning the policy, Azure will automatically enforce the backup configuration on any existing or newly tagged VMs. You can monitor compliance by navigating to the Compliance section within Azure Policy. This section will show you which VMs are compliant (backed up) and which are not.

With Azure Policy and Terraform, you can automate and enforce backup configurations across your VMs effortlessly. By targeting VMs with specific tags, you ensure that only the necessary resources are backed up, saving costs and improving efficiency. This approach not only simplifies backup management but also ensures that your organizational policies are consistently applied.

By following the steps outlined in this guide, you’ll have a robust, automated backup solution that scales with your Azure environment and is easy to manage with Terraform.

Debloat Windows

Debloat Windows From Unnecessary Apps and Services

While the script is tried and tested, I would suggest you proceed with caution as it may break things. I have added caveats where to tread carefully in the steps below, so follow the process without fail. If you have an older computer and want to speed up Windows 11, this may help you a lot. But again, do it at your own risk.

1. First, press the Windows key once and type “powershell” in the Windows search bar. From the search results, click on the “Run as Administrator” option on the right pane.

Debloat Windows 11 From Unnecessary Apps and Services (2021)

2. Next, copy the below command and paste it into the PowerShell window. After that, hit Enter.
It will automatically clone the Windows debloater script and launch the program within a few seconds.

iwr -useb https://christitus.com/win | iex

3. After executing the command, WindowsDebloater will open up, choose to your liking.

Exchange – Useful Powershell Commands

Here is some useful Powershell Commands for reports:

To install the latest public version of the module, run the following command

Set-ExecutionPolicy RemoteSigned
Install-Module -Name ExchangeOnlineManagement
  • To Connect to Exchange Online with Powershell using modern authetication
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline
Disconnect-ExchangeOnline
  • List All Email Adresses in a .txt file

Get-recipient -resultsize unlimited | select Name -expand emailaddresses > c:\emailadresses.txt

  • List All Mailbox Sizes in a .html file

Get-Mailbox –ResultSize Unlimited | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | convertto-html DisplayName, LastLoggedOnUserAccount,  LastLogonTime, TotalItemSize, ItemCount, @{label=”TotalItemSize(MB)”;expression={$_.TotalItemSize.Value.ToMB()}} | set-content c:\mailboxsizes.html

  • List All Mailbox Permissions in a .csv file

Get-Mailbox | Get-MailboxPermission | where {$_.user.tostring() -ne “NT AUTHORITY\SELF” -and $_.IsInherited -eq $false} | Select Identity,User,@{Name=’Access Rights’;Expression={[string]::join(‘, ‘, $_.AccessRights)}} | Export-Csv -NoTypeInformation c:\mailboxpermissions.csv

    Here is some useful Powershell Commands for Database Management:

    • List Mailboxes by mailbox databases

    Get-Mailbox | Sort database, name | Format-Table name, database

    • Move all mailboxes from one database to another database

    1. Launch the Exchange Management Shell > Firstly lets get the names of my Databases, then I can simply copy and paste them into the move mailbox command.

    Get-MailboxDatabase

    Get-Mailbox -Database “Source Database Name” -ResultSize Unlimited | New-MoveRequest -TargetDatabase “Target Database Name

    2. The Mailbox moves should then be queued, depending on how many there are, this can take some time to complete.

    3. To check on progress issue the following command;

    Get-MoveRequestStatistics -MoveRequestQueue “Target Database Name
     

    4. When complete you should remove the movement requests like so;

    Get-MoveRequest | where {$_.status -eq “Completed”} | Remove-MoveRequest
     

    5. That’s all the ‘user’ mailboxes, but your source database server may have system mailboxes in it. These will be either Arbitration mailboxes, or Archive Mailboxes (or both). I don’t have any archive mailboxes, but I do have Arbitration mailboxes. To find out for your databases, use the following commands;

    Get-Mailbox -Database “Source Database Name” -Arbitration

    Get-Mailbox -Database “Source Database Name” -Archive

    6. To move Arbitration and Archive mailboxes, use the following commands;

    Get-Mailbox -Database “Source Database Name” -Arbitration | New-MoveRequest -TargetDatabase “Target Database Name

    Get-Mailbox -Database “Source Database Name” -Archive | New-MoveRequest -TargetDatabase “Target Database Name

    7. Remove all Request

    Get-MoveRequest -ResultSize Unlimited | Remove-MoveRequest -Confirm:$false

    Here is some useful Powershell Commands for Export/Import:

    • Granting User Rights for Mailbox Exports in Exchange 2010

    New-ManagementRoleAssignment -Role “Mailbox Import Export” -User Administrator

    • IMPORT MAILBOX:

    New-MailboxImportRequest -Mailbox “Administrator” -FilePath “\\Exchange\Backup_PSTs\$($i.Alias).pst” 

    • EXPORT MAILBOX:

    New-MailboxExportRequest -Mailbox administrator -FilePath “\\Exchange\Backup_PSTs\$($i.Alias).pst”

    • EXPORT ALL MAILBOXES:

    foreach ($i in (Get-Mailbox)) { New-MailboxExportRequest -Mailbox $i -FilePath “\\Exchange\Backup_PSTs\$($i.Alias).pst” }

    • EXPORT ALL USERS FROM OU:

    foreach ($i in (Get-Mailbox -OrganizationalUnit “domain.dk”)) { New-MailboxExportRequest -Mailbox $i -FilePath “\\Exchange\Backup_PSTs\$($i.Alias).pst” }

    • STATUS OF EXPORT:

    Get-MailboxExportRequest | Get-MailboxExportRequestStatistics

    • REMOVE COMPLETED EXPORT REQUESTS :

    GetMailboxExportRequest -Status Completed | Remove-MailboxExportRequest

    • FULL ACCESS TO ALL MAILBOXES

    Get-Mailbox -ResultSize unlimited -Filter {(RecipientTypeDetails -eq ‘UserMailbox’) -and (Alias -ne ‘Admin’)} | Add-MailboxPermission -User Administrator@domain.dk -AccessRights fullaccess -InheritanceType all

    Setup VPN L2TP/IPsec

    Set up L2TP/IPSec VPN on Windows Server 2019

    Introduction

    A VPN or Virtual Private Network is used to securely tunnel the data from a local computer to a remote server. You can visualize VPN as a private network distributed across the internet or public network. Using VPN, different devices can securely talk to each other as if they are connected over a private network.

    There are various VPN tunneling protocols are available. In this tutorial, we will configure a fresh VPS running Windows Server 2019 as an L2TP over IPSec VPN. L2TP or Layer 2 Tunneling Protocol is a tunneling protocol but it does not provide strong encryption. IPSec comes into picture here, which provides very strong encryption to data exchanged between the remote server and client machine.

    We will leverage on Remote and Remote Access Services (RRAS) which provides easy to use interface to configure networking features such as VPN, NAT, Dial-Up Access server, Lan Routing, etc.

    Prerequisites

    • Cloud VPS or Dedicated Server with Windows Server 2019 installed.
    • You must be logged in via Remote Desktop Protocol as an administrative user.

    Step 1: Update System

    Search for Windows Powershell and open it in Administrative mode by right-clicking and selecting Open as Administrator.

    Install Windows update module for Powershell by running the command.

    Install-Module PSWindowsUpdate

    You may be prompted for confirmation, press Y and enter all the time.
    Now get the list of latest updates by running.

    Get-WindowsUpdate
    Finally, install the updates by running the command.
    
    Install-WindowsUpdate

    Once updates are installed, restart the computer by running the command.

    Restart-Computer

    Step 2: Install Remote Access Role

    Open Powershell again in administrative mode and run the following command to install the Remote Access feature with Direct Access and VPN (RAS) and Routing along with management tools.

    Install-WindowsFeature RemoteAccess
    Install-WindowsFeature DirectAccess-VPN -IncludeManagementTools
    Install-WindowsFeature Routing -IncludeManagementTools

    Step 3: Configure Routing and Remote Access

    Open Server Manager and navigate to Tools >> Remote Access Management.

    On the left pane, right-click on your local server and click Configure and Enable Routing and Remote Access.

    In Configure and Enable Routing and Remote Access Wizard, select Custom Configuration radio button as we will manually configure the routing and access. Click Next button.

    Next, select VPN access and click next to see a summary of the selection.
    *NAT is needed if you have 1 NIC connected with Public wan ip

    Finally, on clicking Finish button, you will see a prompt to start the Routing and Remote Access Services. Click on the Start Service button.

    Step 4: Configure VPN Properties

    Now that we have our VPN running, let’s go ahead and configure it. Under the Routing and Remote Access window, on the left pane, right-click on your local server and click Properties.

    Navigate to the security tab and click on Allow custom IPSec policy for L2TP/IKEv2 connection and put a very long PSK(Pre-shared key). You can use any tool to generate a random key.

    Make sure to note down the PSK as we will need to share the PSK with every user who wants to connect to the VPN server.

    Now, go to IPv4 tab and under IPv4 address assignment select static address pool. Click Add button and you will get a pop up to put IP address ranges. Put the starting address and ending address of the IP address range you want the users to assign to.

    Click the OK button to save the address range and finally click OK to save the changes. You may get a warning saying you need to restart the Routing and Remote Access for changes to apply, you can safely click OK and ignore it for now as we will restart the service after completing next step.

    Step 5: Restart Routing and Remote Access

    On the left pane of Routing and Remote Access window, right-click on your local server and click on Restart under All Tasks.

    This will restart the Routing and Remote Access services and all the changes we have made will be applied.

    Step 6: Configure Windows Firewall

    On the start menu, search for Windows defender firewall and open it. Click on Advanced settings on windows defender firewall.


    Under Advanced setting, click on Inbound Rules on the left pane and then click on New Rule on right side pane.

    Windows Server 2019 has predefined rules which we need to enable for VPN to work. In New Inbound Rule Wizard click on Predefined radio button and select the Routing and Remote Access from the drop-down.

    Under Predefined Rules select Routing and Remote Access(L2TP-In) checkbox and click Next.

    Under Action select, the option Allow the connection and click Finish.

    The firewall is now configured to allow inbound traffic on UDP port 1701.

    Step 7: Configure Internet Facing Firewall

    On the Firewall facing the Internet you will need to open the ports for the traffic to pass through.

    To allow L2TP w/ IPSec traffic, open UDP ports 500, 1701 & 4500

    In the below image you will see an example from a pfSense firewall (the server which holds the Remote Access Role has the ip: 172.21.29.21

    Step 8: Allow VPN User to Connect

    On your VPN users properties, navigate to Dial-in tab. Now, select Allow access option for Network Access Permissions setting. Click OK to save the properties.

    Our L2TP/IPSec VPN server is now ready and can accept the connections.

    Step 9: Monitoring VPN

    Search for Remote Access Management Console in the start menu and open the console. You should see the status of the VPN. If you have followed the tutorial correctly, you will see all green checkmark on all services. You can also view the details of connected clients on this console.

    Tip: Deploy with Powershell

    Open Powershell and run the below commands which holds configuration.

    (In the below command ” c6lWJ%MK=oiKfe” is the PreShared Key)

    Add-VpnConnection -Name "NAME OF VPN" -ServerAddress "vpn.server.dk" -TunnelType "L2tp" -AuthenticationMethod MSChapv2 -UseWinlogonCredential -L2tpPsk c6lWJ%MK=oiKfe
    
    New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\PolicyAgent' -Name 'AssumeUDPEncapsulationContextOnSendRule' -Value "2" -PropertyType DWORD -Force

    Requirement: Add the necessary registry setting:

    1. Press the Windows Key and R at the same time to bring up the Run box.
    2. Type in: regedit and click OK. Click Yes if asked if you’d like to allow the app to make changes to your PC.
    3. In the left pane, locate and click the folder: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PolicyAgent
    4. Click the Edit menu and hover your cursor over New. Click DWORD Value. A new registry will appear in the right pane, named New Value #1.
    5. Rename that file: AssumeUDPEncapsulationContextOnSendRule (this is case-sensitive and contains no spaces) and press ENTER.
    6. Right-click AssumeUDPEncapsulationContextOnSendRule, then click Modify.
    7. In the Value data box, type 2 and click OK.
    8. Reboot the computer.

    Connect to L2TP/IPsec VPN FROM Mac

    Prerequisites

    • Mac OS X
    • Access to your Mac OS X with admin or a user that has administrator permissions

    Step 1 – Log in to Mac OS X

    Click on the  icon in the left top corner and click System Preferences

    macos system

    Click on Network

    macos network

    Click on + to add a new interface

    macos network settings

    Select  VPN via the Interface dropdown list. Select L2TP over IPsec as VPN-type.

    Enter the VPN server information.

    Once everything is entered/selected click Create

    macos plus

    Select VPN (L2TP)in the left menu and enter your VPN information. In our tutorial, we use as example Server Address 193.33.61.185 and we are using Administrator as Account Name.

    macos vpn

    Click on  Authentication Settings... and enter Password in the password field of your VPN user. In our article, it’s the password of the administrator user of our VPN server followed by the Shared Secret that you have entered in step 5 of this article as Preshared key and click on OK

    macos vpn sharedkey

    Click on Advanced...

    macos advanced

    If your VPN server allows sending your traffic through the server, you can enable this to send all traffic over your VPN connection.

    Select Send all traffic over VPN connection to send all traffic over the secure VPN connection.

    macos vpn traffic

    Step 2 – Connect with VPN

    The Mac OS X VPN client is now configured. Click on  Connect to make a connection with your VPN server.

    macos vpn connect

    We have made a successful connection to our VPN server via VPN.

    macos vpn status

    Conclusion

    Congratulations, you have configured a VPN client on a Mac OS X.

    Command Line To Uninstall Software

    Using WMIC:

    • List all installed Programs

    Open Command Prompt as Administrator

    Type

    wmic product get name, version, vendor

    and press Enter.

    After a few moments, a list will be displayed in the command prompt detailing the programs installed on the target computer.

    • If you want to save the results in a .html file

    Type

    wmic /output:%USERPROFILE%\DESKTOP\InstalledSoftware.html product get Name, Version /format:htable

    and press Enter.

    • If you want to uninstall a program from the list
    Echo Y|WMIC Product Where "Name='<INSERT PRODUCT NAME HERE>'" Call Uninstall

    Using MSIEXEC

    Programs installed with an .MSI are easy and has two choices:

    Uninstall Using the Installation MSI

    If you still have access to the .MSI installation file you can simply run:

    msiexec /x <PROGRAM NAME HERE>.msi /q

    Uninstall Using the App’s GUID

    If you don’t have access to the .MSI installation file:

    1. Figure out what the GUID of the program is with this Powershell Command:
      get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize
    2. Either in a CMD window running as an ADMIN or a script running as an ADMIN
      msiexec /quiet /norestart /uninstall {<GUID>}

      like:

      msiexec /quiet /norestart /uninstall {7FCA6452-46F2-452F-A5A7-DAB7DE12D0E6}

    Using PowerShell

    1. You can use the first two steps in e WMIC method above to determine the exact program nae
    2. Use the following commands in a PowerShell running as an admin:
      $app = Get-WmiObject -Class Win32_Product -Filter "Name = '<PROGRAM NAME HERE>'" $app.Uninstall()

    Complete Force Removal of a Domain Controller from Active Directory Guide

    Know Your FSMO Locations

    Make sure that the DC you are removing is not holding any of the FSMO Roles

    i) On any health domain controller, click Start, click Run, type “Ntdsutil” in the Open box, and then click OK
    ii) Type “roles“, and then press ENTER
    iii) Type “connections“, and then press ENTER
    iv) Type “connect to server <servername>“, where <servername> is the name of the server you want to use, and then press ENTER
    v) Type “quit“, and then press ENTER
    vi) Type “select operation target“, and then press ENTER
    vii) Type “list roles for connected server“, and then press ENTER
    viii) Review the listed roles and their host, if the DC that wish to remove is not listed proceed to step 4

    Seizing FSMO Roles (The Last Resort)

    If for what ever reason you can not do a clean transfer you will need to seize it

    i) On any health domain controller, click Start, click Run, type “Ntdsutil” in the Open box, and then click OK
    ii) Type “roles“, and then press ENTER
    iii) Type “connections“, and then press ENTER
    iv) Type “connect to server <servername>“, where <servername> is the name of the server you want to use, and then press ENTER
    v) Type “quit“, and then press ENTER
    vii) Type seize <role>, (where <role> is the role you want to seize)
    viii) You will receive a warning window asking if you want to perform the seize. Click on Yes

    Roles:
    Naming Master
    PDC
    Schema Master
    RID Master
    Infrastructure Master

    ***Note***
    Do not put the Infrastructure Master (IM) role on the same domain controller as the Global Catalog server. If the Infrastructure Master runs on a GC server it will stop updating object information because it does not contain any references to objects that it does not hold. This is because a GC server holds a partial replica of every object in the forest.

    Transferring the any hosted FSMO Roles

    i) For the RID, PDC, and Infrastructure Master
    1. Click Start, point to Programs, point to Administrative Tools, and then click Active Directory Users and Computers.
    2. Right-click the icon next to Active Directory Users and Computers, and then click Connect to Domain Controller.NOTE: If you are not on the domain controller where you want to transfer the role ,you need to take this step. It is not necessary if you are connected to the domain controller whose role you want to transfer.
    3. Click the domain controller which will be the new role holder, and then click OK.
    4. Right-click Active Directory Users and Computers icon, and then click Operation Masters.
    5. In the Change Operations Master dialog box, click the appropriate tab (RID, PDC, or Infrastructure) for the role you want to transfer.
    6. Click Change in the Change Operations Master dialog box.
    7. Click OK to confirm that you want to transfer the role.
    8. Click OK.
    9. Click Cancel to close the dialog box.

    ii) For the Domain Naming Master role
    1. Click Start, point to Programs, point to Administrative Tools, and then click Active Directory Domains and Trusts.
    2. Right-click the Active Directory Domains and Trusts icon, and then click Connect to Domain Controller.NOTE: If you are not on the domain controller where you want to transfer the role ,you need to take this step. It is not necessary if you are connected to the domain controller whose role you want to transfer.
    3. click the domain controller that will be the new role holder, and then click OK.
    4. Right-click Active Directory Domains and Trusts, and then click Operation Masters.
    5. In the Change Operations Master dialog box, click Change.
    6. Click OK to confirm that you want to transfer the role.
    7. Click OK.
    8. Click Cancel to close the dialog box.

    iii) For the Schema Master Role
    1. Click Start, click run, type mmc, and then click OK.
    2. On the Console, menu click Add/Remove Snap-in.
    3. Click Add.
    4. Click Active Directory Schema.
    5. Click Add.
    6. Click Close to close the Add Standalone Snap-in dialog box.
    7. Click OK to add the snap-in to the console.
    8. Right-click the Active Directory Schema icon, and then click Change Domain Controller.NOTE: If you are not on the domain controller where you want to transfer the role ,you need to take this step. It is not necessary if you are connected to the domain controller whose role you want to transfer.
    9. Click Specify Domain Controller, type the name of the domain controller that will be the new role holder, and then click OK.
    10. Right-click Active Directory Schema, and then click Operation Masters.
    11. In the Change Schema Master dialog box, click Change.
    12. Click OK.
    13. Click OK .
    14. Click Cancel to close the dialog box.

    Attempt a Force Removal

    i) As a Domain Admin and in a command prompt type dcpromo /forceremoval
    ii) If the force removal did not work pull the plug ( or shut down properly) and never every turn it back on while connected to the network

    Clear the Metadata from AD

    i) On any health domain controller, click Start, click Run, type “Ntdsutil” in the Open box, and then click OK
    ii) Type “metadata cleanup“, and then press ENTER
    iii) Type “connections“, and then press ENTER
    iv) Type “connect to server <servername>“, where <servername> is the name of the server you want to use, and then press ENTER
    v) Type “quit“, and then press ENTER
    vi) Type “select operation target“, and then press ENTER
    vii) Type “list domains“, and then press ENTER
    viii) Type “select domain [n]”, [n] representing the domain, and then press ENTER
    ix) Type “list sites“, and then press ENTER
    x) Type “select site [n]”, [n] representing the site, and then press ENTERR
    xi) Type “list servers in site“, and then press ENTER
    xii) Type “select server [n]”, [n] representing the DC to be removed, and then press ENTERR
    xiii) Type “quit“, and then press ENTER
    xiv) Type “remove selected server“, and then press ENTER

    Cleanup DNS by Removing all References to the Removed server

    i) In the DNS snap-in, right click domain.whatever and Properties
    1. Click on Nameservers tab: remove server
    ii) Repeat the above instructions for Reverse lookup and all zones
    iii) Open up _msdcs and check all folders within for server name or ip reference
    iv) Repeat the above step for _sites, and all others
    v) Repeat the above steps for the Reverse Lookup Zones

    In Active Directory Sites and Services – delete server

    Configure Domain Controller to synchronize time with external NTP server

    Introduction

    Configure Primary Domain Controller to synchronize time with external NTP server (pool.ntp.org)
    UDP port 123 must be open on firewall to allow NTP traffic in and out from this DC.
    From DC command prompt type “telnet portquiz.net 123” to test if the port 123 traffic can go out.

    Logon to Primary Domain Controller (PDC)

    If you have multiple domain controller and don’t know which DC holds PDC role then use following command:

    netdom /query fsmo

    Configure external time sources

    w32tm /config /reliable:yes /syncfromflags:manual /manualpeerlist:"0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"

    restart w32 time server, now DC should synchronize time with the ntp time servers.

    net stop w32time; net start w32time

    Force domain computers to synchronize the time with the DC; use elevated command prompt

    w32tm /config /syncfromflags:domhier /update

    Following commands will reset the time service to default.

    net stop w32time; w32tm /unregister; w32tm /register; net start w32time
    

    To set the time zone to Denmark in PowerShell, use the Set-TimeZone cmdlet.

    Set-TimeZone -Id "Central European Standard Time"

    w32tm sync commands:

    Force synchronizing the time asap

    w32tm /resync /nowait
     Check NTP configuration
    w32tm /query /configuration
     Check NTP status
    w32tm /query /status /verbose

    Display time source

    w32tm /query /peers

    Display time between Domain Controllers

    w32tm /monitor

    Configure DKIM with Office 365

    Description

    Many administrators are familiar with SPF (Sender Policy Framework) as a system to declare and verify who can send emails from a domain. In the fight against spam and phishing, SPF is not enough anymore.

    DKIM (DomainKeys Identified Mail) is an email authentication system based on asymmetric cryptographic keys. A sending email server signs the message body and/or headers with a private key. A receiving email server verifies the key signature, checking for changes in the message fields. The additional identity verification includes a data integrity component using the signature keys to ensure the original message is arriving intact.

    Applies to:

    Office 365 (O365), Exchange Online, DKIM

    Implicit DKIM Signing in Office 365

    Administrators with domains on an Office 365 tenant already have an implicit DKIM signature applied to the tenant domain. The tenant domain is the “.onmicrosoft.com” domain, sometimes called the initial domain. Microsoft does this because it controls the DNS for onmicrosoft.com, publishing the public key and storing the private key on behalf of all subscribed tenants. The implicit signing is the basis of creating an explicit signature for your primary domain, the one without the onmicrosoft.com portion.

    Implementing DKIM with Office 365

    Preparation

    • This article assumes you have access to the Office 365 Admin Center for the tenant domain you are managing.
    • You must have access to the domain’s public DNS zone.

    Office 365 Admin Center Prep

    1. Login to the O365 Admin Center and open the Exchange Admin Center 
    2. From the Exchange Admin Center, click on Protection > DKIM 

      Click on the domain and notice the right-side information bar shows the status is “Not signing DKIM signatures for this domain”.Click on the Enable link to turn on explicit DKIM signing on the primary domain.
    3. Note down the information from the yellow pop-up and add it in a Cname record as described below.

    Add Two CNAME Records

    Depending on the DNS zone management tool being used, the steps below provide the data needed for adding the CNAME records.

    1. Log into the DNS zone management tool for the domain you are working on. 
    2. Add two CNAME records with the following information:
      • 1st CNAME Record
        Host Name: selector1._domainkey.<yourdomain>
        Points to: selector1-<domainGUID>._domainkey.<tenantDomain>
      • 2nd CNAME Record
        Host Name: selector2._domainkey.<yourdomain>
        Points to: selector2-<domainGUID>._domainkey.<tenantDomain>

    You can also get your DKIM Records by connecting to Exchange Online via Powershell and running this command:
    Get-DkimSigningConfig -Identity <domain> | Format-List Selector1CNAME, Selector2CNAME

    Enable DKIM Signing for the Domain in Office 365

    1. Go back to the O365 Admin Center and open the Exchange Admin Center as shown in Figure 3.
    2. From the Exchange Admin Center, click on Protection > DKIM as shown in Figure 4.
    3. Click on the primary domain and notice the right-side information bar shows the status is “Not signing DKIM signatures for this domain” as shown in Figure 5.Since the CNAME records have been added to your domain’s DNS zone the signing of messages for the domain can be enabled. Click on the Enable link to turn on explicit DKIM signing on the primary domain.

    Flash Drive with Multiple Versions of Windows

    How to Create a Master Installation Flash Drive with Multiple Versions of Windows

    wmi_top

    You’ve got your collection of Windows ISOs and maybe you’ve burned installation DVDs or flash drives for them. But why not make yourself a master installation drive that you can use to install any version of Windows?

    Setting up a bootable USB Drive that includes multiple ISOs is actually pretty easy, We’re going to do it using a clever little free tool named WinSetupFromUSB, so go ahead and download the latest version of that. You can even include some non-windows ISOs on the disk, like Linux distributions and antivirus rescue disks. For a complete list of what you can include on your USB drive, check out their supported sources page. There is one important note from that page worth calling out. The tool works with single Windows ISOs from Microsoft. If you have a dual ISO that includes both the 32-bit and 64-bit versions of Windows, you won’t be able to use it. But you can always download single ISOs (one for 32-bit and one for 64-bit) and stick them both on the USB if you need to.

    Next, make sure you have blank USB drive big enough to hold all the ISOs you want to install, along with a little extra space. A 16 GB drive should give you enough space for two or three versions of Windows. If you have a 32 GB drive, you should be able to fit all the versions of Windows you could want. If you want to include other ISOs as well, you might need a bigger drive.

    WinSetupFromUSB is a portable tool, so there’s no installation. Once you have it downloaded, double-click the archive to extract the files a new folder. If you’re running a 64-bit version of Windows, run the executable with “x64” in the name. If you’re running a 32-bit version of Windows, run the file without the “x64” in the name.

    wmi_1

    If you already had your USB drive inserted when you launched the tool, it should be listed in the box at the top of the window. If you didn’t have it inserted already, go ahead and plug it in now and then click Refresh.

    wmi_2

    Next, click the “Advanced Options” check box.

    wmi_3

    Instead of working like a regular check box, clicking it opens an “Advanced Options” dialog box. In the Advanced Options dialog, select the “Custom menu names for Vista/7/8/10/Server Source” check box. This setting allows you to provide your own names for the folders in which the Windows ISOs are stored and the boot menu names you see when you start a computer using the USB drive. You can close the “Advanced options” dialog when you’re done.

    wmi_4

    Now comes the somewhat tricky part. You’ll be adding Windows versions one at a time. The first time you add something to the USB drive (and only the first time), you’ll want to make sure that the “Auto format it with FBinst” check box is selected. This lets WinSetupFromUSB format the drive appropriately for booting. If you know you’ll be booting a computer in UEFI mode (or if you’re unsure), then select the “FAT32” option. Otherwise, you can use the “NTFS” option.

    wmi_5

    Next, select your first Windows ISO. Select the check box next to the “Windows Vista / 7 / 8 / 10 /Server 2008/2012 based ISO” section and then click the browse button (“…”) to its right. Locate and open the ISO you want to add.

    wmi_6

    If it’s a large ISO and you’re using the FAT32 file system, you may get a notification that the file is too large and will be split in two. That’s fine, so go ahead and click OK.

    wmi_7

    Double-check that you have the correct USB drive selected at the top of the window and that the right ISO is shown in the box. Then, click “GO.”

    wmi_8

    If you’re using a large USB drive, you may get a warning asking if you’re sure that’s the drive you want to use. Go ahead and click “Yes.”

    wmi_9

    If the auto format option is enabled (and it should be for the first ISO you add to a disk), you’ll also get a warning letting you know that the drive will be formatted and anything on it will be erased. Click “Yes” to continue.

    wmi_10

    WinSetupFromUSB will now format the drive and then pop up a window where you can enter a custom folder name for the ISO that’s between 1 and 7 characters. If you don’t type anything for 30 seconds, the default will be used automatically.

    wmi_11

    A similar window will now open that lets you type a custom name that should appear in the boot menu. This time, the name can be between 5 and 35 characters, so you have a bit more room to be specific. And again, you have 30 seconds to type a new name before the default is used automatically.

    wmi_12

    At this point, WinSetupFromUSB will begin creating folders, adding the ISO to your USB drive, and adding the options to the boot menu. This can take several minutes and you can gauge the progress in the window’s status bar.

    wmi_13

    When WinSetupFromUSB is done, you’ll get a simple “Job done” confirmation window. Click “OK.”

    wmi_14

    WinSetupFromUSB now returns you to the main window. You can exit the program or you can continue adding additional ISOs to your boot disk. You’ll add additional ISOs using the same process, but there are a couple of things to keep in mind as you do it:

    • When you add additional ISOs to an existing boot disk, make sure the “Auto format it with FBinst” check box is not selected. It won’t be by default when you return to the window (or when you start the program again), but it doesn’t hurt to make sure. You only want to format the disk with the very first ISO you add.
    • You’ll need to click “Advanced Options” and enable the “Custom menu names for Vista/7/8/10/Server Source” check box each time you add a new ISO. Make sure you don’t forget this step before clicking Go or you won’t be able to add a custom name for the ISO to your menu.

    But that’s it. Otherwise, just follow the same steps each time you want to add a new ISO to the boot disk. You don’t have to add them all in one session either. You can come back any time and add something new. When you’re done, you can boot up a computer using your USB drive (which you may be able to do even if your BIOS won’t let you) and be rewarded with a nice boot menu like this:

    wmi_15

    While it doesn’t sport the most intuitive interface, WinSetupFromUSB is lightweight and works well. And once you get the hang of adding ISOs to the package, it’s a breeze to set yourself up with a powerful boot disk that will let you install whatever version of Windows you want, as well as a number of other bootable tools.