Export multiple Windows Server 2012 R2 Hyper-V Guests with PowerShell Part I

After spending many hours building out multiple Hyper-V guests there’s always a chance that something will go wrong and you’ll be needing a backup to restore from.  There are many options available, but suffice it to say that while useful, Checkpoints & Replication are not backups.

So what are the other options?  The simplest is an Hyper-V Export to another location.  The more robust solution is using System Center 2012 R2 Data Protection Manager, [which I’ll begin to cover in Part III].

Now, while we can manually Export… any guest from Hyper-V Manager wouldn’t it be nice to be able to query the list of machines and then Export… them one by one to a location on an automated basis using Task Scheduler?

Before we get into the PowerShell to accomplish this task, I’d like to point out that Microsoft still has not provided an –Overwrite switch on the Export-VM command.  Thus if you want to repeat this process and keep multiple weeks or a months backups you’ll have to find another option for if the files/folders exist the Export-VM command will fail to execute.  So what’s a possible solution?  Create a folder with a current data/time stamp to hold all of the exported machines and then do this each time the PowerShell command executes.  Simple right?  Well, keep in mind that after awhile these folders will pile up and you’ll also need a method of deleting old ones as well depending upon how long you want to store them. 


In the example above a separate drive D: has been designated as the Export location and a folder called Exports has been created to store each export based upon the data/time the Task Scheduler task executes the PowerShell script.

The first step in the PowerShell script is to query the list of existing folders and then removes the folder older than one month from the current date/time.  This keeps 5 backups and helps reduce the disk space required for the backups.  [NOTE:  System Center 2012 R2 Data Protection Manager can significantly reduce backup disk space consumption, but we’ll cover that in Part III.]

So let’s look at a simple script to accomplish the above, with a single machine, then we’ll get fancy (in Part II) skirting some other issues that result from exporting multiple machines at one time and the disk I/O, we’ll also address the SLA issue of 99.9% availability for the machines you want to backup, etc.

First the assumptions:

  • We have only one guest machine we want to export/backup.
  • It is OK to stop the guest machine while we back it up and then we’ll restart it after the export is complete.
  • It only takes 3 minutes to shutdown the guest machine properly.

The simple PowerShell script below will accomplish this task given the assumptions above.


# $RootPath: Can be changed to point where you’d like the Virtual Machines exported and can be any valid

#            drive path.

$RootPath = ‘D:\Exports\’

# $OutputDate: Is simply used to create a unique folder name that later can have it’s CreationDate checked

#              for deletion later.

$OutputDate = (Get-Date).Year.ToString() + ‘.’ + (Get-Date).Month.ToString() + ‘.’ + (Get-Date).Day.ToString() + ‘.’ + (Get-Date).Hour.ToString() + ‘.’ + (Get-Date).Minute.ToString() + ‘.’ + (Get-Date).Second.ToString()


$GuestVMName = “GuestVirtualMachineName”




    Stop-VM -Name $GuestVMName

    Start-Sleep -Seconds 180








#Clean up old Export-VM folders older than one month ago to reduce disk space consumption.

foreach ($i in Get-ChildItem $RootPath)


    if ($i.CreationTime -lt ($(Get-Date).AddMonths(-1)))


            #Write-Output $i.Name.ToString()

            Remove-Item $i.PSPath -Recurse




#Create new Export folder with current date/time.

$ExportPath = New-Item ($RootPath + ‘ ‘ + $OutputDate) -type directory


#Export the VM.

Export-VM -ComputerName $env:COMPUTERNAME -Name $GuestVMName -Path $ExportPath


#Start the VM.



    Start-Sleep -Seconds 180

    Start-VM -Name $GuestVMName








Adding this PowerShell to Task Scheduler and setting up a schedule provides an easy way to backup this single guest machine on a regular basis.

In Part II of this series, we’ll get into a more real world example of how to accomplish this for multiple guests and ensure that we’re exporting only one machine at a time to ensure quality disk I/O on the destination disk.  In Part III, we’ll get into System Center 2012 R2 Data Protection Manager.

Tagged with:
Posted in Hyper-V, PowerShell, Windows Server 2012 R2

Create A Windows Server 2012 R2 Hyper-V Machine with PowerShell

Creating a new guest hyper-v image using the Hyper-V Manager can become tedious after awhile especially when the need arises for creating an entire lab environment consisting of multiple guests all in one shot.

Using PowerShell to accomplish a task like this is the answer.  What follows is a very simple example that can be used to create more elaborate solutions toward that goal.  The intent is to demonstrate some of the basics while leaving the more elaborate solution (parameters, multiple guests, etc.) as an exercise for the reader.

NOTE:  Since the title of this article is Windows Server 2012 R2, this is not intended to function on Windows Server 2012.

This example creates a dual (2) CPU, 2GB RAM, guest with drive C: and a second drive (in this case a DC for storage of SYSVOL and NTDS), sets up the DVD drive with an .iso for installation of the OS, uses the default Network Adapter and creates a second for private use.


# Create the Virtual Machine

New-VM -Name RonBokDC01 -MemoryStartupBytes 2048MB -Path D:\HyperV\RonBokDC01 -Generation 2


# Create the Virtual Machines Required Disks

New-VHD -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\RonBokDC01.vhdx’ -SizeBytes 127GB -Dynamic

New-VHD -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\Data.vhdx’ -SizeBytes 127GB -Dynamic


# Attach the Virtual Machines Disks to the SCSI Controller

Add-VMHardDiskDrive -VMName RonBokDC01 -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\RonBokDC01.vhdx’ -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0

Add-VMHardDiskDrive -VMName RonBokDC01 -Path ‘D:\HyperV\RonBokDC01\Virtual Hard Disks\Data.vhdx’ -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 1


# Attach the Windows Server 2012 R2 .iso to the DVD for installation.

Set-VMDvdDrive -VMName RonBokDC01 -ControllerNumber 1 -Path ‘E:\Downloads\MSDN\Operating Systems\en_windows_server_2012_r2_x64_dvd_2707946.iso’


#Get the first Network Adapter, usally named ‘Network Adapter’ and attach it to the Public NIC of the VM Host.

$NetAdapter = Get-VMNetworkAdapter -VMName RonBokDC01

$NetAdapterName = $NetAdapter.Name

Connect-VMNetworkAdapter -VMName RonBokDC01 -Name $NetAdapterName -SwitchName ‘Intel(R) 82574L Gigabit Network Connection – Virtual Switch’


#Rename the first Network Adapter to Public.

Rename-VMNetworkAdapter -VMName RonBokDC01 -Name $NetAdapterName -NewName ‘Public’


#Add another Network Adapter called Private and attach it to the Private Network Switch.

Add-VMNetworkAdapter -VMName RonBokDC01 -Name ‘Private’ -IsLegacy $false -SwitchName ‘Private’


#Set Processors

Set-VMProcessor -VMName RonBokDC01 -Count 2


Tagged with: , ,
Posted in Hyper-V, PowerShell, Windows Server 2012 R2

Microsoft AD FS SAML Assertion Trouble Shooting w/Fiddler

When working with multiple Relying-Party’s / Service Providers in AD FS it often becomes necessary to ensure that the Saml Assertions / Claims being sent are indeed being sent.  By using the IdpInitiatedSingon.aspx page included with AD FS 2.1 on Windows Server 2012 and Fiddler together the Saml Assertions / Claims can be inspected and confirmed.


Requirements & Assumptions

Teleriks Fiddler Tool w/SSL Capture Enabled

A functional Microsoft AD FS 2.1 Farm on Windows Server 2012 with or without an AD FS Proxy.

The known endpoint of your AD FS Farm:  https://sts.domain.com/

At least one Relying Party Trust with a Service Provider configured to send a few claims.

When creating the Relying Party Trust, you chose NOT to encrypt the claims.

Add-ADFSRelyingPartyTrust  … -EncryptClaims $False

Credentials in the domain in which the AD FS Farm resides.

SAML 2.0 Web SSO Protocol is being used, not WS-Federation Passive Protocol.


Step 1 – Get Authenticated by AD FS in your domain


Browse to https://sts.domain.com/adfs/ls/IdpInitiatedSignOn.aspx.



Click, Continue to Sign In.


Type your domain credentials as shown.  This user should have Windows Credentials in the domain to which the ADFS Farm is joined.  Click, Sign In.


Step 2 – Select a Relying Party Trust / Service Provider to Test




To test our POST to our Relying Party, select it from the Select one of the following sites: drop down.


Step 3 – Get ready to capture the Fiddler session

Start, Fiddler to being your trace.

Once Fiddler is running and ready to capture your trace, click the Go button.


Step 4 – Review the Fiddler Session Capture to locate your SAML Token.


In Fiddler, look for the GET request that looks like, https://sts.domain.com/adfs/ls?SAMLRequest= …. and select that item in the Fiddler session panel.

Select Inspectors in Fiddler, and select TextView.

Look for a section contained in this POST that looks like:

<input type=”hidden” name=”SAMLResponse” value=” …. lots of base 64 encoded values … “/><noscript><p>Script is disabled. Click Submit to continue.</p><input type=”submit” value=”Submit” /></noscript></form><script language=”javascript”>window.setTimeout(‘document.forms[0].submit()’, 0);</script></body></html>



It is the base 64 encoded string between the two quotes …. lots of base 64 encoded values … , that we want to carefully select in Fiddler with our cursor.

After selecting the text detailed above, right-click on the text and send it to the Fiddler TextWizard. Once loaded into the TextWizard, select the radio button From Base64 to decode the POST into readable format.  This is your SAML Token.


It will include your AD FS Token-Signing Certificate and toward the very bottom of the XML, will include a section where your assertions / claims will be visible:

  <Attribute Name=”http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress”>
  <Attribute Name=”http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth”>

If you do not see any claims, then your Claims Rules are not being processed for this user account.  To trouble shoot your Claims Rules, a good starting point is add a static Issue Rule like the one described on TechNet.

=> issue(type = “http://test/role&#8221;, value = “employee”);

If you do not see any claims,Then, simply retest using the steps above until you are certain that the SAML Assertions / Claims you want passed are indeed being passed.

Tagged with: ,
Posted in AD FS, Windows Server 2012

Demoting and removing a Domain Controller from a Forest

There are particular situations where moving or removing a Domain Controller responsible for a Active Directory Forest/Domain might be desired. For example, when upgrading from one version of Windows Server to another without doing an in-place upgrade and/or getting prepared to run the ADPREP tool.

In order to accomplish this you need to determine which Domain Controllers have ownership over the particular Flexible Single Master Operations (FSMO) roles (also known as operations master roles) in use by Active Directory.

In a forest, there are at least five FSMO roles that are assigned to one or more domain controllers. The five FSMO roles are:

  1. Schema Master: The schema master domain controller controls all updates and modifications to the schema. To update the schema of a forest, you must have access to the schema master. There can be only one schema master in the whole forest.
  2. Domain naming master: The domain naming master domain controller controls the addition or removal of domains in the forest. There can be only one domain naming master in the whole forest.
  3. Infrastructure Master: The infrastructure is responsible for updating references from objects in its domain to objects in other domains. At any one time, there can be only one domain controller acting as the infrastructure master in each domain.
  4. Relative ID (RID) Master: The RID master is responsible for processing RID pool requests from all domain controllers in a particular domain. At any one time, there can be only one domain controller acting as the RID master in the domain.
  5. PDC Emulator: The PDC emulator is a domain controller that advertises itself as the primary domain controller (PDC) to workstations, member servers, and domain controllers that are running earlier versions of Windows. For example, if the domain contains computers that are not running Microsoft Windows XP Professional or Microsoft Windows 2000 client software, or if it contains Microsoft Windows NT backup domain controllers, the PDC emulator master acts as a Windows NT PDC. It is also the Domain Master Browser, and it handles password discrepancies. At any one time, there can be only one domain controller acting as the PDC emulator master in each domain in the forest.

There are many methods for this, but there are some PowerShell commands that can be run to determine this as well as some diagnostics tools as well as some MMC SnapIn’s as well which are documented on TechNet.

First lets find the PDC Emulator using PowerShell on Windows Server 2012:

Get-ADDomainController -Discover -Service PrimaryDC

Domain      : ronbok.us

Forest      : ronbok.us

HostName    : {RONBOKDC2.ronbok.us}

IPv4Address :

IPv6Address :

Name        : RONBOKDC2

Site        : Default-First-Site-Name


Continuing with PowerShell, the following command would have been very useful, however it does appear to fall short in that it does not return any results for our SchemaMaster or DomainNamingMaster. While I have no confirmation of this yet, it appears to be a bug with this command:

Get-ADDomain ronbok.us | FT PDCEmulator,RIDMaster,InfrastructureMaster,SchemaMaster,DomainNamingMaster


PDCEmulator                  RIDMaster                    InfrastructureMaster        SchemaMaster                DomainNamingMaster        

———–                  ———                    ——————–        ————                ——————        

RONBOKDC2.ronbok.us          RONBOKDC2.ronbok.us          RONBOKDC2.ronbok.us         {}                          {}                        

Instead, we can use DCDiag or DSQuery to determine all the FSMO roles and which DC’s currently own them:

DCdiag /test:Knowsofroleholders /v

Starting test: KnowsOfRoleHolders


         Role Schema Owner = CN=NTDS Settings,CN=RONBOKDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ronbok,DC=us

         Role Domain Owner = CN=NTDS Settings,CN=RONBOKDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ronbok,DC=us

         Role PDC Owner = CN=NTDS Settings,CN=RONBOKDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ronbok,DC=us

         Role Rid Owner = CN=NTDS Settings,CN=RONBOKDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ronbok,DC=us

         Role Infrastructure Update Owner = CN=NTDS Settings,CN=RONBOKDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=


         ……………………. RONBOKDC1 passed test KnowsOfRoleHolders


dsquery server -hasfsmo pdc

dsquery server -hasfsmo rid

dsquery server -hasfsmo infr

dsquery server -hasfsmo schema

dsquery server -hasfsmo name

Now that you’ve determined which DC owns which role, we can move them to newly built Domain Controllers that may exist in your environment.  So, by example, if I built out a Windows Server 2012 R2 DC (RonBokDC1) as part of the same domain and now want to move all roles to it the following PowerShell command would be useful:

#Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole PDCEmulator, RIDMaster, InfrastructureMaster, SchemaMaster, DomainNamingMaster


Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole PDCEmulator

Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole RIDMaster

Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole InfrastructureMaster

Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole SchemaMaster

Move-ADDirectoryServerOperationMasterRole -Identity “RonBokDC1” -OperationMasterRole DomainNamingMaster

Now, once that’s completed I can finally demote the old RonBokDC2 and remove it from the domain.  That’s it!

Tagged with: , , ,
Posted in Windows Server 2012

Windows Server 2012 Error: 0x800f0922 installing updates from Windows Update


  • You’re running Windows Server 2012 R2 as a HyperV host.
  • You’re trying to use Windows Update for a Windows Server 2012 guest running on that host…
    • …and Windows Update keeps failing to install the updates and rolls the server back…only to show that the updates failed leaving you back where you started.


As it turns out this is a very unique situation that isn’t well documented and if you’ve arrived here you’re fortunate because finding the solution to this difficult issue using Bing or Google is challenging at best.

It turns out that a single update KB2871690 from Microsoft is the root cause under these very specific circumstances, and the solution is now well documented here.

In my specific case I had a Domain Controller running Windows Server 2012 as a HyperV guest on a Windows Server 2012 R2 host, that would not take this update.

Simply put, adding the Bitlocker feature on the Domain Controller, rebooting, and then running this update singularly from Windows Update succeeded in getting this update applied.  Once applied you can remove the feature.

Alternatively, if you do not want to install the Bitlocker feature, simply disable Secure Boot on the HyperV guest as shown below, then re-enable Secure Boot after the update is applied.


Tagged with: , , ,
Posted in Windows Server 2012

How to move Windows Azure Active Directory Sync (DirSync) from one machine / VM to another…


One of the critical tasks ahead for on boarding your organization to Microsoft’s Office 365 (O365) will be to determine your identity strategy.  In fact, whether your on boarding to O365 or not, having a strategy in place will help determine the path to take when and if you decide to take advantage of Microsoft’s Software As A Service (SaaS) model encompassed by the capabilities in O365.

Early on, either during a Fast Track Pilot (Pilot –> Deploy –> Enhance) or a pilot you may run yourself,  you will want to get up and running as quickly as possible to experience all that O365 has to offer.  Often that means creating separate ‘Cloud Accounts’ (In Cloud) that have no coorelation to the Active Directory accounts used within your organization.

Later, as you move through to Step 2 Deploy of Fast Track or the next step in your own project plan, you will want to enable the use of your own organizational identity.  This isn’t Single-Sign-On (SSO), but a simple way to duplicate/replicate your organizational identity to O365/Windows Azure Active Directory enabling things like account and password synchronization.  It is also a prequiste for true SSO with Active Directory Federation Services (AD FS). To do this you will employ the use of Windows Azure Active Directory Sync (WAADS) affectionally known as DirSync from its downloadable executable name – dirsync.exe.

Often customer take a shortcut in implementing WAADS by installing the components (Forefront Identity Manager 2010 R2 or FIM) onto a Domain Controller (DC) which became a supported scenario last year by Microsoft.  For smaller organizations this might be the only option when server resources are in short supply.  Later as they grow or are able to invest in an additional resources the desire to create a dedicated WAADS machine (physical or virtual) becomes desirable.  However, moving and removing WAADS from the DC can be a little tricky and is not documented on TechNet by Microsoft at this time.

What follows is a set of steps that can be followed to accomplish this task – keeping your current FIM Filtering in place and reusing you’re existing WAADS service accounts that get created during installation.


You have a single ADDS forest tied to a public domain and two domain controllers DomainDC1 and DomainDC2.  Originally WAADS was installed on DomainDC1 and now you want to create a new member server DomainDirSync and move the existing implementation of WAADS to this machine from DomainDC1.  Keep in mind that WAADS/DirSync is also filtering by OU.

  1. Create the new DomianDirSync machine/VM w/Windows Server 2012 R2.
  2. Join DomainDirSync to Forest.
  3. Stop or disable WAADS/DirSync on the existing DomainDC1.
  4. Install WAADS and import the exported settings from the DomianDC1 to DomainDirSync machine/VM
  5. Uninstall WAADS/DirSync from the DomainDC1.
  6. Clean up domain service account(s) created by the installation of WAADS/DirSync on DomainDC1.
  7. Clean up the uninstall process of WAADS/DirSync on DomainDC1.


Backup your existing FIM (formerly MIIS) settings:

On DomainDC1 start the MIISClient “C:\Program Files\Windows Azure Active Directory Sync\SYNCBUS\Synchronization Service\UIShell\miisclient.exe”

Select File –> Export Server Configuration… and create a folder to save off the FIM settings.  You will import these settings to the newly created DomainDirSync machine once dirsync.exe has been installed and configured there.  NOTE:  Be prepared to keep track of where you saved this exported configuration and copy it to the DomainDirSync machine later.

Export FIM Configuration Settings...

Export FIM Configuration Settings…

In Active Directory Users and Computers, on DomainDC1 or any other DC look for an make note of the names of two accounts:


Why?  One of these accounts will get disabled and later deleted (AAD_) as they are the service accounts being used by WAADS/DirSync instance running on DomainDC1 which we are going to replace.  MSOL_ will get reused if we import our prior settings.   Note that two new accounts will be created when building DomainDirSync.  The MSOL_ and AAD_ accounts.   The AAD_ account will no longer be a domain account, but a local machine account on DomainDirSync.  The MSOL_ account that gets created in domain will ONLY be used if we don’t import our prior settings and reconfigure our AD Filters in FIM manually.  If we import our FIM Filters, then we will get prompted for our original MSOL_ accounts password.  If you don’t know the MSOL_ account password, and most likely you don’t, you can set it in Active Directory Users and Computers now.

Next, build DomainDirSync using Windows Server 2012 or Windows Server 2012 R2 (See References section below for details.)  NOTE:  You will need to enable the .NET 3.5 Framework feature and run Windows Update to get .NET 3.5 SP1 installed prior to attempting to install dirsync.exe.

Install dirsync.exe, but DO NOT launch it.  It’s OK to Configure it, but we don’t want to execute a Sync until we’re done importing the exported configuration (above).  We will need to import the exported server configuration (above) and disable the Windows Service on DomainDC1 that is used by the FIM 2010 R2 (Windows Azure Active Directory Sync Service) so that DomainDC1 is temporarily disabled from synchronizing with O365.

Click Next>

Click Next>

When the install is finished you can start the Configuration.

Click Next>

Click Next>

Not being a tutorial on how to install DirSync you’ll follow the steps you did before including entering your O365 Global Administrator account credentials,  your Active Director Domain Account credentials, most likely enabling Password Sync (checkbox).

Click Next>

Click Next>

WARNING:  Uncheck the Synchronize your directories now checkbox!

Uncheck and Click Finish

Uncheck and Click Finish

Now, before executing a sync we need to stop the WAADS/DirSync Windows Service on DomainDC1.  To do this use Administrative Tools –> Services, look for and stop the Windows Azure Active Directory Sync Service.

While in Services you’ll notice that this service runs under a domain account that begins with ADD_.  We won’t need this account any longer once we uninstall WAADS/DirSync from DomainDC1.  Also note that there is another account in the domain that begins with MSOL_ and again you NEED to know this account and it’s password.  If you don’t know the password (as already mentioned), then just use Active Directory Users and Computers on DomainDC1 to set it to something you know.

Now that the new machine or VM, DomainDirSync is ready to go, let’s import our exported settings from DomainDC1 (at the very beginning of this post).  Copy the folder over to DomainDirSync and as before start the MIISClient “C:\Program Files\Windows Azure Active Directory Sync\SYNCBUS\Synchronization Service\UIShell\miisclient.exe” on DomainDirSync.

To import, Select File –> Import Server Configuration… and when prompted put in your OLD MSOL_ accounts password (the one you set earlier, you did set it right?)  to finish the import process.

Import finished, Click OK.

Import finished, Click OK.

Finally we can execute a manual WAADS/DirSync with O365 by executing manually a Start-OnlineCoexistenceSync from the FIM PowerShell “C:\Program Files\Windows Azure Active Directory Sync\DirSyncConfigShell.psc1”.

We should see a full sync occur and everything should be working normally again.  Last, but not least you need to disable / delete the newly created domain MSOL_ account and the old ADD_ domain accounts leaving the original MSOL_ account in the domain.

Then, finally, we can uninstall Windows Azure Active Directory Sync from DomainDC1.  When you do, you’ll have to manually delete the C:\Program Files\Windows Azure Active Directory Sync\ folder and its contents, since the uninstall fails to do so.


Tagged with: , , ,
Posted in Office 365