Live Migrate VM´s in Hyper-V cluster from RC to RTM node

Yesterday I upgraded a Hyper-V node in a cluster from RC to RTM, Now I want to live migrate VM´s from the RC node to the RTM and then upgrade that.

As you can see on this screendump I have one node with build number 8400 (RC) and one with 9200 (RTM)

As you can see on this next image I have two VM´s running on my old node and I want to migrate them. The VM´s reside on a SMB 3.0 share and the cluster have a quorum share

And how do I move the VM´s to the other node, yes with powershell also, what you can see is that the Move-ClusterVirtualMachineRole can take the VMid from the VM objects as pipelined input, and that is really nice.

So now I have live migrated over the VM´s from the old RC to the RTM server and I can continue to upgrade that node.

I get an error if I try to live migrate them back to the old node, the only way I can do that is when the VM´s are powered off.


Using PowerShell to get/start VM´s from Hyper-V servers in Active Directory

Of course I would rather have all my hosts in my System Center VMM 2012 SP1 but if I do not, or I just as an ITPro admin want to check if there are some new Hyper-V servers out there in my Active Directory and if they have VM´s on them I can use PowerShell.

I have looked at Ravikanth´s blog and done some modifications, also I am using the Win2012 and Powershell v3.

I can with the following powershell cmd get all hyper-v virtual machines in my Active Directory (of some reason the VMware machines do not get registered in the AD as virtual machines). With powershell version 3 it autoloads the Active Directory Module, this requires though that I have the feature RSAT-AD-PowerShell installed, easily done with Get-WindowsFeature RSAT-AD-PowerShell | Add-WindowsFeature.

Get-ADObject -Filter 'Name -like "*Virtual*"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") }

I cannot do so much more with this information, what I want is to check a list of Hyper-V servers and also try to get the VM´s on them, sadly only win2012 servers can interact with the hyper-v powershell module and give that info, but hey whom has win 2008 r2 hyper-v servers 😉

This first query gives me all Hyper-V servers in the domain, 2008->2012

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") }

This next query uses that info and asks the Hyper-V servers for their VM´s

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") } | %{get-vm -ComputerName $_ -ErrorAction SilentlyContinue} | ft ComputerName,Name,State,Uptime -AutoSize

I can also use this to do things with the VM´s, like starting or stopping, observe that i just want to start the VM´s that start with the name test*.

Get-ADObject -Filter 'Name -like "*Hyper-V"' | %{$_.DistinguishedName.Split(",")[1].replace("CN=","") } | %{get-vm test* -ComputerName $_ -ErrorAction SilentlyContinue} | Start-VM

Set up non-admin account to access WMI and performance data remotely with PowerShell

I am working in a project that want to get performance data from remote servers, this with WMI, the servers belong to an Active Directory but the user collecting is not allowed to be an administrator (As an Administrator this is easy because then you already are in control and in the right groups)

So How do I fix this with preferably PowerShell, Scripting Guy has made a post about how to add users to local groups and Steve Lee on the MSDN WMI Blog has made a post how to add permissions on WMI  so I have combined them and got the solution I want.

The groups I am interested in on the remote computer are  “Distributed COM Users”,”Performance Monitor Users”, to be able to connect and get monitoring data

To get it from the WMI interface I need some permissions there, I only grant read permissions on the root/CIMv2 subtree.

And here is the Powershell that does it, In the screendump you can see that I can use a foreach loop to set the permissions on several computers

# Create Permissions for non-admin user on remote computers
# Niklas Akerlund / 2012-08-22
Param ([switch]$add,
    $ComputerName = "vc",
    $UserName = "olle",
    $DomainName = "vniklas")

# add functions to call
. .\Set-UserLocalGroup.ps1
. .\Set-WmiNamespaceSecurity.ps1

$LocalGroups = "Distributed COM Users","Performance Monitor Users"

if ($add){
	$LocalGroups | %{Set-UserLocalGroup -Computer $ComputerName -Group $_ -Domain $DomainName -User $UserName -add}
	Set-WMINamespaceSecurity root/CIMv2 add "$DomainName\$UserName" Enable,MethodExecute,ReadSecurity,RemoteAccess -computer $ComputerName
} elseif($remove) {
	$LocalGroups | %{Set-UserLocalGroup -Computer $ComputerName -Group $_ -Domain $DomainName -User $UserName -remove}
	Set-WMINamespaceSecurity root/cimv2 delete "$DomainName\$UserName" -computer $ComputerName

To check that I can get the performance data I can use the powershell cmdlet Get-WMIObject , as you can see in the screendump, in the first test I do not have the permissions set but in the second it works..

Here are the functions


# Add/Remove user from local group 		
# Niklas Akerlund/Most code from Scriptingguy Blog

Function Set-UserLocalGroup 
	$de = [ADSI]"WinNT://$Computer/$Group,group" 
	} elseif ($remove){

Set-WmiNamespaceSecurity, there was an error in the original code that I have corrected based on the comments, this error caused the function to always run on the local computer instead of the remote when using the -computer parameter.

# Copyright (c) Microsoft Corporation.  All rights reserved. 
# For personal use only.  Provided AS IS and WITH ALL FAULTS.
# Set-WmiNamespaceSecurity.ps1
# Example: Set-WmiNamespaceSecurity root/cimv2 add steve Enable,RemoteAccess
Function Set-WmiNamespaceSecurity {
Param ( [parameter(Mandatory=$true,Position=0)][string] $namespace,
    [parameter(Mandatory=$true,Position=1)][string] $operation,
    [parameter(Mandatory=$true,Position=2)][string] $account,
    [parameter(Position=3)][string[]] $permissions = $null,
    [bool] $allowInherit = $false,
    [bool] $deny = $false,
    [string] $computer = ".",
    [System.Management.Automation.PSCredential] $credential = $null)
Process {
    $ErrorActionPreference = "Stop"
    Function Get-AccessMaskFromPermission($permissions) {
        $WBEM_ENABLE            = 1
                $WBEM_METHOD_EXECUTE = 2
                $WBEM_FULL_WRITE_REP   = 4
                $WBEM_PARTIAL_WRITE_REP              = 8
                $WBEM_WRITE_PROVIDER   = 0x10
                $WBEM_REMOTE_ACCESS    = 0x20
                $WBEM_RIGHT_SUBSCRIBE = 0x40
                $WBEM_RIGHT_PUBLISH      = 0x80
        	$READ_CONTROL = 0x20000
        	$WRITE_DAC = 0x40000
        $WBEM_RIGHTS_STRINGS = "Enable","MethodExecute","FullWrite","PartialWrite",<code>
        $permissionTable = @{}
        for ($i = 0; $i -lt $WBEM_RIGHTS_FLAGS.Length; $i++) {
            $permissionTable.Add($WBEM_RIGHTS_STRINGS[$i].ToLower(), $WBEM_RIGHTS_FLAGS[$i])
        $accessMask = 0
        foreach ($permission in $permissions) {
            if (-not $permissionTable.ContainsKey($permission.ToLower())) {
                throw "Unknown permission: $permission</code>nValid permissions: $($permissionTable.Keys)"
            $accessMask += $permissionTable[$permission.ToLower()]
    if ($PSBoundParameters.ContainsKey("Credential")) {
        $remoteparams = @{ComputerName=$computer;Credential=$credential}
    } else {
        $remoteparams = @{ComputerName=$computerName}
    $invokeparams = @{Namespace=$namespace;Path="__systemsecurity=@"} + $remoteParams
    $output = Invoke-WmiMethod @invokeparams -Name GetSecurityDescriptor
    if ($output.ReturnValue -ne 0) {
        throw "GetSecurityDescriptor failed: $($output.ReturnValue)"
    $acl = $output.Descriptor
    $computerName = (Get-WmiObject @remoteparams Win32_ComputerSystem).Name
    if ($account.Contains('\')) {
        $domainaccount = $account.Split('\')
        $domain = $domainaccount[0]
        if (($domain -eq ".") -or ($domain -eq "BUILTIN")) {
            $domain = $computerName
        $accountname = $domainaccount[1]
    } elseif ($account.Contains('@')) {
        $domainaccount = $account.Split('@')
        $domain = $domainaccount[1].Split('.')[0]
        $accountname = $domainaccount[0]
    } else {
        $domain = $computerName
        $accountname = $account
    $getparams = @{Class="Win32_Account";Filter="Domain='$domain' and Name='$accountname'"}
    $win32account = Get-WmiObject @getparams
    if ($win32account -eq $null) {
        throw "Account was not found: $account"
    switch ($operation) {
        "add" {
            if ($permissions -eq $null) {
                throw "-Permissions must be specified for an add operation"
            $accessMask = Get-AccessMaskFromPermission($permissions)
            $ace = (New-Object System.Management.ManagementClass("win32_Ace")).CreateInstance()
            $ace.AccessMask = $accessMask
            if ($allowInherit) {
            } else {
                $ace.AceFlags = 0
            $trustee = (New-Object System.Management.ManagementClass("win32_Trustee")).CreateInstance()
            $trustee.SidString = $win32account.Sid
            $ace.Trustee = $trustee
            $ACCESS_ALLOWED_ACE_TYPE = 0x0
            $ACCESS_DENIED_ACE_TYPE = 0x1
            if ($deny) {
                $ace.AceType = $ACCESS_DENIED_ACE_TYPE
            } else {
                $ace.AceType = $ACCESS_ALLOWED_ACE_TYPE
            $acl.DACL += $ace.psobject.immediateBaseObject
        "delete" {
            if ($permissions -ne $null) {
                throw "Permissions cannot be specified for a delete operation"
            [System.Management.ManagementBaseObject[]]$newDACL = @()
            foreach ($ace in $acl.DACL) {
                if ($ace.Trustee.SidString -ne $win32account.Sid) {
                    $newDACL += $ace.psobject.immediateBaseObject
            $acl.DACL = $newDACL.psobject.immediateBaseObject
        default {
            throw "Unknown operation: $operation`nAllowed operations: add delete"
    $setparams = @{Name="SetSecurityDescriptor";ArgumentList=$acl.psobject.immediateBaseObject} + $invokeParams
    $output = Invoke-WmiMethod @setparams
    if ($output.ReturnValue -ne 0) {
        throw "SetSecurityDescriptor failed: $($output.ReturnValue)"


Updated: Change to Powershell console in Windows 2012 Core

This friday I wrote a post about how to change from CMD to powershell and also found Thomas Lee´s posts about it.

What i wrote in my post was that i found the registry key that holds the command prompt but could not alter it. Andrew Morgan had already done all in his post, he also describes how you do, the secret is to take the ownership of the registry part (otherwise it is TrustedInstaller that is owner and that was why I could not change anything), after you change owner you also want to add some permissions, cause Administrator has only read by default.


And why do I want to add an registry key under AlternateShell instead of the Shell registry key that holds Explorer.exe. One reason is that when I enable the GUI from Core mode I do not get the full GUI. So when I run Get-WindowsFeature *gui-shell* | Add-WindowsFeature and then reboot the server it looks like the following screendump:

As you can see in the following screendump and in Andrew´s post, I keep the CMD and just set an new registry key that has a higher value, but not as high as Explorer. Doing this I get the Powershell console when in Core and the Explorer when in Full GUI mode. When in full GUI mode I get a temporary Pagefile error though 🙁 , the system seems to work correctly.. I have tested the Get-WindowsFeature *gui-shell* | Add-WindowsFeature on an installation where I have not done any alternation with the shells and there the page file dialog appears also so this is caused by another issue that I will investigate in another blog post.


Change to Powershell console in Windows 2012 Core instead of CMD

In twitter yesterday I saw that there was a discussion about setting default shell to Powershell in Windows Core, Jeffery Hicks has done this in Windows 2008 R2 and I wanted to test if his little trick worked in Windows 2012 also (by the way, why is it not default by default in 2012 Core? )

I have my testmachine ready and so lets go

Interestingly, When I check the registry I got that my shell in the 2012 Core was Explorer.exe,

but when I got a bit deeper I could see under AlternativeShells that the CMD was there

I tried to edit that but got an error 🙁

well lets try to exchange the explorer.exe in shell  to powershell.exe instead, I use the $env:userprofile to get the same directory as with cmd

$shell = "Powershell.exe -NoExit cd <code>$env:userprofile"
set-itemproperty "hklm:\software\microsoft\windows nt\currentversion\winlogon" shell $shell

And here you can see in my registry, notice that the $env:userprofile is still there thanks to the in the string variable and that means that when another user log in they will get their own directory:

 And when I try to log in again I get the Powershell Console by default and also in the “right” directory

Lets hope Microsoft set Powershell console as default also in the Core version when Windows 2012 becomes RTM 🙂

Update: I did apparently not follow the tweets so far that I noticed that the PS master Thomas Lee already had made a blog about this, in his post I would just add this to get the users directory

Set-ItemProperty -Confirm  -Path $RegPath -Name Shell -Value 'PowerShell.exe -noExit -Command "$psversiontable; cd $env:userprofile"' 

Clone VM on Win 2012 Hyper-V v3 when it is running using Powershell

I wanted to create a function that could help an IT Pro Admin with the task to create a clone of a running VM, Yes you can use the Export-VM cmdlet but then your VM must be turned off and in some cases, for example when you want to test a new release or patch on a production system but first test it in a safe environment and you are not allowed to stop the original VM.

The function exists in System Center Virtual Machine Manager but there it also must be turned off

So how do I do? I have made a PowerShell function that take a snapshot, copies the vhd files and creates a new VM, connect the vhd´s and network cards, configures the VM with number of processors, dynamic memory etc.

As the Snapshot merges the vhdx files when the VM is running in this new Hyper-V version I thought it was an sufficient way to solve that the VM actually was not writing to the .vhdx files when I copy them but into the .avhdx diff file.

This is a version 0.1 and yes it need some development but right now I do not have the time to make it supernice,

Here you can see it in action

And when It is finished It looks like this in the gui

And here is the PowerShell function

   Function to clone a running VM
   This function can be used to clone a running vm and connect the copied vhd´s and network
   Clone-VM -VMName vmdisktest -VMCloneName vmdisktest-clone -Path c:\VMs
   Clone-VM -VMName vmdisktest -VMCloneName vmdisktest-clone -Path c:\VMs -Switch Private
Author: Niklas Akerlund
Date: 2012-06-19
function Clone-VM
        # Name of the VM to be cloned
        [string] $VMCloneName,
        # Where to store the VM-clone 
        [string] $Path,
        # Set to another network switch
        [string] $Switch = " "    

    # Get VM
    $VM = Get-VM $VMName
    $VHDs = Get-VMHardDiskDrive -VM $VM
    #$VHDPath = (Get-VMHardDiskDrive -VM $VM).Path
    $VHDClonePath = "$Path\$VMCloneName\Virtual Hard Disks\"
    # Create a new array of VHD info
    $VHDOrg = @()
    foreach ($VHD in $VHDs){
        $data = New-Object PSObject -property @{
            VHDName = (Get-Item $VHD.Path).Name
            VHDPath = $VHD.Path
            ControllerType = $VHD.ControllerType
            ControllerNumber = $VHD.ControllerNumber
            ControllerLocation = $VHD.ControllerLocation

        $VHDOrg +=$data

    $VMNics = Get-VMNetworkAdapter -VM $VM

    # Take snapshot 
    $VM | Checkpoint-VM 

    New-Item -ItemType directory -Path $VHDClonePath

    New-VM -Name $VMCloneName -Path $Path -NoVHD -MemoryStartupBytes $VM.MemoryStartup -BootDevice IDE
    $VMClone = Get-VM -Name $VMCloneName
    Get-VMNetworkAdapter -VMName $VMCloneName | Remove-VMNetworkAdapter
    # Configure VM-Clon
    if ($VM.DynamicMemoryEnabled){
        Set-VM -VMName $VMCloneName -ProcessorCount $VM.ProcessorCount -DynamicMemory -MemoryMinimumBytes $VM.MemoryMinimum -MemoryMaximumBytes $VM.MemoryMaximum
        Set-VM -VMName $VMCloneName -ProcessorCount $VM.ProcessorCount -StaticMemory

    # Add all network cards
    foreach ($VMNic in $VMNics){
        if ($Switch -eq " "){
            Add-VMNetworkAdapter -VMName $VMCloneName -SwitchName $VMNic.SwitchName -IsLegacy $VMNic.IsLegacy
            Add-VMNetworkAdapter -VMName $VMCloneName -SwitchName $Switch -IsLegacy $VMNic.IsLegacy

    # Copy all VHDs
    foreach ($VHDcopy in $VHDOrg){
        $Dest = $VHDClonePath + $VHDcopy.VHDName
        Copy-Item -Path $VHDcopy.VHDPath -Destination $Dest
        Add-VMHardDiskDrive -VMName $VMCloneName -ControllerType $VHDCopy.ControllerType -ControllerLocation $VHDCopy.ControllerLocation  -ControllerNumber $VHDCopy.ControllerNumber -Path $Dest   

    # Remove snapshot 
    $VM | Remove-VMSnapshot


Good luck in testing, but do take in consideration that this is an copy of the running VM so do not start it at the same time on the same network or you will get IP collision etc, as you can see above I have added an -Switch parameter that you can use to set the network cards of the VM to be connected on another switch to avoid any problems.. 🙂

Using Powershell v3 scheduling for off hours Hyper-V VM maintenance/configuring

A colleague wanted a script for a reconfiguration of a VM´s settings. Once the VM is powered off that is not a big issue. The smart thing is when using Powershell version 3 I can configure a scheduled job that I want to execute off hours.

Imagine that you have the task to add a vCPU to a VM but you can only do it during the service window that happens to be around midnight, I don´t know about you but I rather sleep then if I can automate it. Yes I could in earlier versions use scheduled task but now I am using Win 2012 and Hyper-V 3 and the latest powershell.

So what do I need to do then, Jan Egil Ring has made a blog post about scheduled jobs and I want to show an example regarding Virtual Machine management..

In Powershell version 3 there are 16 cmdlets regarding scheduled jobs

First I need a Trigger

$once = New-JobTrigger -Once -At 11:59PM

Then I need a job with the trigger, I could use a parameter -FilePath to use a script file instead of -ScriptBlock

Register-ScheduledJob -ScriptBlock {$vm = Get-VM TestVM2 ; Stop-VM -VM $vm ; Set-VM -VM $vm -ProcessorCount 2 ; Start-VM -VM $vm} -Trigger $once

And then just wait or sleep 😛

And here you can see a screendump of the changing, Now I changed the trigger time to not have to wait to midnight for the blog post but I think you can imagine…

To check that the Job went ok, you run the cmdlet Get-Job ( and if you do not get any job you might need to run import-module PSScheduledJob to get the right Get-Job in that session)

God luck in scheduling your VM tasks 🙂

Lets remove some VM´s with PowerShell on Hyper-V 3 in Windows 2012

In the PowerCLI world there is a kind of evil oneliner to remove all VM´s from a datacenter, I was searching for something alike in the Hyper-V v3 world

The PowerCLI command is

Get-VM | %{Stop-VM $_ -Confirm:$false; Remove-VM $_ -DeletePermanently -Confirm:$false

And of course that is pure evil because the parameter -deletepermanently will remove not only the VM but also it´s files from the datastore, The % is to take care of each VM and in case the VM is running I will shut it down (otherwise if I only run like Get-VM | Stop-VM -Confirm:$false | Remove-VM -deletePermanently -Confirm:$false I will only remove the ones running, cause I will get an error on the others because I cannot change state to what it is already)

In Hyper-V and the powershell v3 It is not quite as easy but of course it can be done and don´t you dare use the gui 😉

This approach requires that you have put your VM in a separate folder for each of them (or of course it will be clean in your default Hyper-V VM folder..)

The Remove-VM cmdlet does not allow you to actually remove the VM´s virtual hard disk and the folders (which in some times can become a bit messy after a while)

Here is my VM´s

And here is my folder

So if I remove one VM now with the Remove-VM TestVM1, this also requires that the VM is off.

And lets see in the folders what do we have

So to clean both VM´s and folder data I run all at once and this looks like this

Get-VM testvm* | %{ Stop-VM -VM $_ -Force; Remove-VM -vm $_ -Force ; Remove-Item -Path $_.Path -Recurse -Force}

And see in my VM´s folder how tidy and neat it is 😛

And as I started to describe in the top .. If you just use Get-VM | …  you will clean your Hyper-V host quick 🙂

PowerCLI installed on Windows2012 and working in PS Webaccess

Today my adventures continues, I had to test and install the PowerCLI on a Windows 2012 RC to see if it works and also if it could be used in the new Windows 2012 feature PowerShell Webaccess.

In an earlier post I showed how to configure the PowerShell Webaccess, then I was not successful to run the PowerCLI, the difference here is that I now installed the PowerCLI on the Win 2012 server.

To be able to install i had to enable the .net 2.0 (why the PowerCLI is built on that version is another discussion we will not go into here), as you can see on the dialog I had to enable that

Ok, and that should be done with PowerShell or? My server did not have an active Internet connection so I got a failure when trying to enable the .Net Framework, I had to use the Dism tool with the install media to get the .Net installed as it otherwise downloads the files necessary from MS.

dism /online /enable-feature /featurename:NetFx3 /all /source:D:\sources\sxs

When this is enabled then there was no problem installing the PowerCLI and when installed I can use for example the V3 functions Get-VM | where powerstate -eq “PoweredOn” <- notice I am not using any curly brackets and $_

Now to the Webaccess, I connect to the site and log on with an authorized account. After that I run Add-PSSnapin VMware.VimAutomation.Core to enable the PowerCLI functionality . Then i need to get the credential before connecting to the vCenter because the pswa could not show the promt for credential.

But that is easily fixed by using $cred = Get-Credential and then Connect-VIServer -Credential $cred 🙂 and as you can see I can now connect and use the PowerCLI in a web browser.

May the PowerCLI be with you!

Using Powershell v3 Workflow with HyperV deployment

Now that the Windows 2012 RC has arrived with the Powershell v3 I wanted to explore the functionality a bit more, I have seen some posts about how to use the Workflows but none when deploying VM´s in Hyper-V.

I have loaned some code from Mikael Nyström (Deployment Bunny) but had to rewrite a little to make it work with the workflow -parallel.

Also when I downloaded Mikael´s scripts they where automatically  blocked ( I had set my demo system to -Unrestricted) but as you see in the screenshot they are still blocked. but luckily I can use the Unblock-File cmdlet in the Powershell v3, when using the v2 there was a utility tool streams.exe from SysInternals that could help.

and here is it in the properties dialog

But if I have like 5-10 or 100 files I would like to use Powershell (Anyone out there unblocking like 100 scriptfiles by clicking in a dialog?)

To create the “Master” vhdx I used the Convert-WindowsImage.ps1 script, I am creating the master to be deployed with win 2012 RC datacenter core version (Updated:I got a tip in the comments to look at the Convert-WindowsImage instead of the Wim2VHD.ps1)

Now to my workflow, I am testing to create 5 VM´s at the same time with differential disks connected to the master. the workflows also set all VM´s to dynamic memory and starts them.

# Inparallel.ps1
# Niklas Akerlund
# 2012-06-03

workflow create-VMs
    $VMRefDisk = "C:\VMs\master.vhdx"
    $VMNetwork = "Intern"
    $VMBaseLocation = "C:\VMs"
    $VMMemory = 384MB
    foreach -parallel ($item in 1..5) {
        $VMName = "TestVM$item"    
        $VMLocation = New-Item -Path "$VMBaseLocation\$VMName" -ItemType Directory -Force
        $VMDiskLocation = New-Item -Path "$VMLocation\Virtual Hard Disks" -ItemType Directory -Force
        $VMDisk01 = New-VHD –Path $VMDiskLocation\$VMName-OSDisk.vhdx -Differencing –ParentPath $VMRefDisk 
        New-VM –Name $VMname –MemoryStartupBytes $VMMemory –VHDPath $VMDisk01.path -SwitchName $VMNetwork -Path $VMBaseLocation
        Set-VM -VMName $VMName -DynamicMemory

        Start-VM -VMName $VMName
    Get-VM TestVM*

It is quite simple but still powerfull, If I for example had like more hosts i can deploy many VM´s at the same time and the thing that would stop me is the hardware and the storage 😛