Getting files out of a running VM in Hyper-V 2012 remotely

January 9th, 2013 No comments

I was reading the post by Ben Virtual-PC Guy about how to get files out of a running virtual machine.

I have altered his bits to work also when not running on a Hyper-V host (as Mount-VHD does not work when not Hyper-V is enabled), and you have the VM´s on a smb share, this also works if you take a snapshot and then copy the vhdx file to a windows 8 or windows 2012 machine.

The cool part is that I can use a UNC share path with Mount-DiskImage which is the Cmdlet used.

If I have the right permissions I can then easily with just a PowerShell script as Ben showed mount the virtual harddisk and copy the files, and this from a remote server and not on the Hyper-V host.

Screen Shot 2013-01-09 at 23.28.25

Get-VM core -ComputerName hv01 | Checkpoint-VM -SnapshotName "Need to look at these disks" -Passthru | %{Get-VHD -VMId $_.vmid -ComputerName $_.ComputerName} | %{Mount-DiskImage -ImagePath $_.ParentPath -Access ReadOnly -PassThru}

After I have run this you see that I can then get the secret file out of the running virtual machine

Screen Shot 2013-01-09 at 16.35.22

and when I am finished copying the secret files from the running virtual machine I can unmount the disk and remove the snapshot.

 Screen Shot 2013-01-09 at 23.29.26

PS C:\> Get-VM Core -ComputerName HV01 | Get-VMSnapshot | %{Get-VHD -VMId $_.vmid -ComputerName $_.ComputerName; Remove-VMSnapshot -VMName $_.VMName -ComputerName $_.ComputerName} | %{Dismount-DiskImage $_.ParentPath -PassThru}

So what is the conclusion on this in a security perspective, as you can see it is quite easy for a person with the right permissions on a host level to get access of files that he or she maybe not should see. Talented hackers can get permissions and accounts that they need. This leads to the discussion of course where you should put your hosts, is it enough security and boundaries on your network and in your Active Directory Domain or should you set up another for the Hyper-V hosts and management servers?!

Bug in Powershell v3 on regional settings in Windows 2012

January 9th, 2013 No comments

In my previos post I was claiming that there was a bug in the Get-WinEvent, but the bug is in Powershell v3 and how it works with the regional settings.

I live in Sweden and thus have Sweden as regional format setting and that did Powershell version 3 not like, at least not for the Get-WinEvent cmdlet :-P

Screen Shot 2013-01-09 at 14.02.22

Using powershell to change the format or culture is done with the following

Screen Shot 2013-01-09 at 14.05.06

Set-Culture en-US

Screen Shot 2013-01-09 at 14.13.54

And when I open a new PowerShell Console I can see the messages for my Hyper-V events :-) not so good with the bug though..

Screen Shot 2013-01-09 at 14.18.58

Lets hope there is a bug fix soon, a bit embarrassing when some parts of the powershell console is not working in other regional settings besides en-US, are we in other parts of the world not that important or just an mistake by an developer, lets hope for the later..

A big thanks to Andreas Hultgren that was first to let me know about the bug :-)

Categories: Powershell, Win2012 Tags:

Bug in Get-WinEvent on Windows 2012?

January 9th, 2013 No comments

I have been trying to get some Events out of my test environment for some Hyper-V stuff.

What I have noticed when digging down into the Get-EventLog and Get-WinEvent I get different information

The Get-EventLog gives me information and message about the Windows Logs and there it works nicely as you can see

Screen Shot 2013-01-09 at 12.14.07

But when I try to get information from as in this case Hyper-V logs with Get-WinEvent I get no information in the fields LevelDisplayName and Messages?!

Screen Shot 2013-01-09 at 12.21.57

And in the Event Viewer you can see that the information is there:

Screen Shot 2013-01-09 at 12.27.14

Have I misunderstood something how to get the Events in PowerShell or is there a bug in the system? In the old “Windows 2008 R2″ I got the information correctly as you can see on this screendump, so the Get-WinEvent issue is related to Win 2012 version!

 Screen Shot 2013-01-09 at 12.40.54

It kind of sucks if I cannot search the messages for some data and collect that information, and what I can see it seems to be the same case for all application and services logs and I will not accept to have to go the Event Viewer GUI :-)


Categories: Hyper-V, Powershell, Virtualization, Win2012 Tags:

Populate your own custom properties on SC VMM 2012

December 17th, 2012 No comments

I have been helping a customer to populate their VMM 2012 console with information that they think is good to have, I have made a blog post about this some time ago but now I have added some new valuable information.

The information I retrive are where the VM resides on what CSV volume, if the VM has dynamic VHD´s, if the VM has snapshots and if the snapshots also have been merged, this can only happen when the VM is in Saved State or Stopped on a Win 2008 R2 Hyper-V (this is not an issue on a win 2012 hyper-v as it can live merge)

First I add the Custom Properties

New-SCCustomProperty -Name "DynamicVHD" -AddMember "VM"
New-SCCustomProperty -Name "Snapshots" -AddMember "VM"
New-SCCustomProperty -Name "Datastore" -AddMember "VM"

Here is a screenshot how it looks when you add the custom properties to the console,
Screen Shot 2012-12-17 at 19.41.55

In the powershell script I iterate down through all the snapshots/differencing disks to the parent VHD and check if that is fixed or dynamic. And as you see in the image I check if there is a snapshot or a removed but not merged snapshot (I still have a small problem with the VMM name Checkpoint ;-) )

# Update custom items Snapshots and Dynamic disks, Datastore
# Niklas Akerlund / Lumagate 2012-12-17
if (-not (Get-Module virtualmachinemanager)) {
    Import-Module virtualmachinemanager
Get-SCVMMServer -ComputerName localhost | Out-Null

$VMs = Get-VM 

foreach ($VM in $VMs){
    $Datastore = " "
    $LocationProp = Get-SCCustomProperty -Name "Datastore"
    $SnapShots = Get-SCCustomProperty -Name "Snapshots"    
    $VHDs = $VM | Get-VirtualHardDisk
    $DynDisk = Get-SCCustomProperty -Name "DynamicVHD" 
    $Dyn = $false
    $Merge = $false
    foreach ($VHD in $VHDs){
        if ($VHD.VHDType -eq "DynamicallyExpanding"){
            $Dyn = $true
        if (($VHD.Location -like "*.avhd") -and (($VM | Get-SCVMCheckpoint) -eq $null)){
                $Merge = $true
        $VHDp = $VHD
        while ($VHDp.ParentDisk -ne $Null){
            $VHDp = $VHDp.ParentDisk
            if($VHDp.VHDType -eq "DynamicallyExpanding"){
                $Dyn = $true
    # Update custom values
    $Datastore = $VM.Location.Split("\")[2]
    Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $LocationProp -Value $Datastore
    if ($Dyn){
        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $DynDisk -Value "Yes" 
        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $DynDisk -Value "No" 
    if ($VM | Get-SCVMCheckpoint){
        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $SnapShots -Value "Yes"
        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $SnapShots -Value "Not Merged"
        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $SnapShots -Value "No"

As I described in the earlier post you can schedule this to run with scheduled tasks and maybe set it to run every hour or what ever you might prefer.

Categories: Automation, Hyper-V, SCVMM, Virtualization Tags:

SCVMM vCheck updated plugin for CSV status reporting

December 9th, 2012 No comments

After visiting a customer this friday we talked about their environment and the need to check that their cluster shared volumes in a Windows 2008 R2 SP1 Hyper-V cluster was healthy.

They have started to take host level backup but have not yet got the hardware VSS driver in place and when we checked the backup agent had got into a faulty state and locked the CSV volume in redirected access mode. When we restarted the backup agent  the status got back to online.

Aidian Finn has done a white paper about backup and CSV volumes which describes the redirection and what that can make for impact on the performance. But in short, the cluster node that is the owner will during the redirected access have sole write access to the CSV volume and that means that the other nodes in the cluster must send all storage trafic to that node.

Alan Renouf´s vCheck script is a really easy and good way to keep in a daily control  of your environment, it works for both a VMware vSphere environment and also for Hyper-V with SCVMM thanks to Jan Egil Ring. The best way is to configure it with scheduled tasks and to send a mail every morning.

What I have done is editing the Cluster Shared Volume check plugin to report the status also, as this can be quite important. It is just a minor addition to the plugin, I have also chosen to change so if you set it to 100 the CSV part will always be included in the report and not depending on a percentage space remaining.

Here is the code for the CSV Plugin:

# Start of Settings
# Free space threshold for Hyper-V Cluster Shared Volumes (value in percent)
$CSVFreeSpaceThreshold ="50"
# End of Settings

$Title = "Hyper-V Cluster Shared Volumes"
$Header ="Hyper-V Cluster Shared Volumes"
if($CSVFreeSpaceThreshold -eq 100){
     $Comments = "Hyper-V Cluster Shared Volumes information and state"
    $Comments = "Hyper-V Cluster Shared Volumes with less than $CSVFreeSpaceThreshold percent free, information and state"
$Display = "Table"
$Author = "Jan Egil Ring/Niklas Akerlund"
$PluginVersion = 1.1
$PluginCategory = "Hyper-V"

$FailoverClusters = $VMHostClusters | Where-Object {$_.VirtualizationPlatform -eq "HyperV"}

if ($FailoverClusters)  {

if (!(Get-Module FailoverClusters)) {
	Import-Module FailoverClusters

foreach ($cluster in $FailoverClusters) {
    if($CSVFreeSpaceThreshold -eq 100){
      Get-ClusterSharedVolume -Cluster $ | Select-Object -Property Name,State -ExpandProperty SharedVolumeInfo | Select-Object @{Name="Cluster";e={$}},Name,FriendlyVolumeName,@{ Label= "State"; Expression ={if($_.RedirectedAccess){"Redirected Access"}elseif($_.MaintenanceMode){"Maintenance Mode"}else{"Online"}}},@{ Label = "Size(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.Size/1024/1024/1024) } },@{ Label = "PercentFree" ; Expression = { "{0:N2}" -f ($_.Partition.PercentFree) } },@{ Label = "FreeSpace(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.FreeSpace/1024/1024/1024) } },@{ Label = "UsedSpace(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.UsedSpace/1024/1024/1024) } }
        Get-ClusterSharedVolume -Cluster $ | Select-Object -Property Name,State -ExpandProperty SharedVolumeInfo | Where-Object {$_.Partition.PercentFree -lt $CSVFreeSpaceThreshold} | Select-Object @{Name="Cluster";e={$}},Name,FriendlyVolumeName,@{ Label= "State"; Expression ={if($_.RedirectedAccess){"Redirected Access"}elseif($_.MaintenanceMode){"Maintenance Mode"}else{"Online"}}},@{ Label = "Size(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.Size/1024/1024/1024) } },@{ Label = "PercentFree" ; Expression = { "{0:N2}" -f ($_.Partition.PercentFree) } },@{ Label = "FreeSpace(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.FreeSpace/1024/1024/1024) } },@{ Label = "UsedSpace(GB)" ; Expression = { "{0:N2}" -f ($_.Partition.UsedSpace/1024/1024/1024) } }
Categories: Hyper-V, Powershell, SCVMM, Virtualization Tags:

Powershell article about log files analysis

December 7th, 2012 No comments

I had a task in an assignment in a recent month about handling massive amounts of logs and did an article that was published on the PowerShell Magazine :-)

The logs are quite unique but you can see some of the new powershell v3 features that I am using for analysis and calculations.

here is the article :

Categories: Powershell Tags:

Schedule Hyper-V VM replication for non-office hours with PowerShell

November 30th, 2012 2 comments

If you have set up Hyper-V replica and are replicating your VM´s to a disaster site or maybe a branch office and that office might have a small WAN connection to the datacenter and you cannot get a faster connection from the ISP and for example you might want to stop the replication during the office hours and resume it on the night you can use the new Powershell version 3 feature scheduled jobs.

This will of course imply on your recovery when there was a disaster. But this can be compared to having an offsite DPM server that you sync to every 24 hours.

Anyway, if you want, you can enable a scheduled job that suspends and resumes a VM replication. I created earlier a blog post about setting up scheduled jobs. The following Cmdlets am I using in this case:

  • Suspend-VMReplication
  • Resume-VMReplication

A simple example, I have a VM that I am currently replicating and want it to be suspended during the day and then resumed when all my users have gone home and I have all bandwidth again.

First I add a replication receiver host for my replicated servers

PS C:\> Set-VMReplicationServer -ComputerName HV02 -ReplicationEnabled $true -AllowedAuthenticationType Kerberos -ReplicationAllowedFromAnyServer $true -DefaultStorageLocation c:\VMs

And then I need to set up the VM replication

PS C:\> Enable-VMReplication -VMName Brun12 -ReplicaServerName -ReplicaServerPort 80 -AuthenticationType Kerberos -ComputerName

PS C:\> Start-VMInitialReplication -VMName brun12 -ComputerName HV01

So How do I schedule then, as you can see on my screendumps, I have used other times for my scheduled jobs than you might want in your environment, you can also use other parameters than -Daily . Use Get-Help New-JobTrigger -full to get the help and there you can see all the options

PS C:\> $cred = Get-Credential

PS C:\> $dailystop = New-JobTrigger -Daily -At 14:10
PS C:\> Register-ScheduledJob -Name StopRepl -ScriptBlock { Suspend-VMReplication -VMName Brun12 -ComputerName HV01 } -Trigger $dailystop -Credential $cred

PS C:\> $dailystart = New-JobTrigger -Daily -At 14:15
PS C:\> Register-ScheduledJob -Name StartRepl -ScriptBlock { Resume-VMReplication -VMName Brun12 -Resynchronize -ComputerName HV01 } -Trigger $dailystart -Credential $cred

And here on this screendump you can see that it works,

Another minor detail, If you have a VM that changes lot of data on the virtual disks during the day, it will take a while for the resyncing after a longer suspension.

Categories: Automation, Hyper-V, Virtualization, Win2012 Tags:

Using the SC Orchestrator 2012 Sp1 to handle Azure

November 28th, 2012 No comments

After I had installed and configured the System Center Orchestrator 2012 SP1 I wanted to evaluate and test how it works to create runbooks for my Azure subscription

As you can see on this link the prerequisite to get this working is

  • System Center Orchestrator 2012 SP1
  • Azure (well kind of obvious or? ;-))

Also to get the connection working to Azure we need a x.509 certificate that we upload to the management site. The first x.509 certificate I tested did not work. Then I created one with another trial certification tool

The only thing that was negative with this tool, the cert is only valid for one month. I will make a cert with openssl instead but that another time!

When I have uploaded the certificate in the Azure Management site it looks like this,

So now when I had a certificate I can configure the Orchestrator, I need the password for the .pfx and then also the path as you can see in the configuration dialog, and last but not least the subscription ID for my Azure subscription.

Then we are prepared for the creation of a Azure Runbook. In this technet page you can see what we can do with the IP for Azure. My first example is very simple, I look for a specific VM role and start that one just to see that I can connect and execute stuff in the cloud, and as you can see I successfully find my VM and started it.

One thing that was not totally clear was the different properties that was to be entered, If I omitted one of the properties or entered a wrong value I got an error.

Now I have a trial subscription but if you have a paid plan one of the ideas of a runbook could be that you start or shut down some VM´s  at different times when you are using them. Each Visual Studio with MSDN license (except the test) that you buy have Azure compute hours that can be used and then of course you do want to have a bit control of them, and one way could be with SC Orchestrator or via Powershell cmdlets for Azure.

Categories: Automation, Virtualization Tags:

Installing SC Orchestrator 2012 SP1

November 27th, 2012 No comments

Today I have been exploring the SC Orchestrator and its functionality with Hyper-V 2012 and SC VMM 2o12 SP1. First of all to get it installed I had to run the installations in “run-as” otherwise it failed during the wizard. I installed it on a Windows 2012, and one prerequisite is that you have the .net 3.5 installed also.

One annoying thing is when you add Integration Packs, unlike for example Operations Manager and importing management packs, you can only add one IP at a time when importing.. And if you want to add like 10-20 first time it is a bit tedious! Please fix that in the RTM.

Another thing that I encountered was an error I did not first understand. When I had added the SCVMM 2012 SP1 IP and wanted to use it, I first added some configuration data but apparently it was not enough cause when I tried to use it I got an error

So what was the error, I had not entered the VMM Console information in the following configuration dialog and apparently the IP uses Powershell under the hood and connects to the powershell console with the vmm module.

When that was configured correctly I could continue to create my first runbook, look at this link to get some SCORCH examples (really handy to get the idea of how to use it and that in runbook examples to have in your Orchestrator designer)

Here is an easy example, I enter a VM name and if the state is “Running” I stop it, and if the state is Stopped I start the VM:

I have been using Powershell quite a bit and not looking so much at the Orchestrator but it is really easy to get up and creating your runbooks. Try it out and see for yourselves.

Categories: SCVMM, Virtualization, Win2012 Tags:

SCVMM 2012 Evacuate VMHost and maintenance script

November 25th, 2012 2 comments

A customer found the bug that exists in the System Center Virtual Machine Managers function for setting a host in maintenance mode. The bug is that when you set a host in maintenance mode it will live migrate all VM´s to the next node in the cluster. This is kind of impractical when you for example want to patch the Hosts and you end up with the last host that is filled with in worst case all  VM´s on it and it takes longer time to live migrate them. The VMM bug should be fixed in the SC SP1 that is coming soon This of course depending on if you have enabled the Dynamic Optimization, that function helps you with the distribution but that will take some time before it runs.

He made a script for evacuating the host and distributing the VMs to the other nodes in the cluster. I have added a bit of logic that also set the host group to not allow dynamic optimization during the scripted evacuation.

The load balancing in my script is quite easy because right now the only thing I look at is the host memory and migrate the VM to the Host that has most memory left at the moment.

   A function to evacuate a host in vmm and set it in maintence mode
   This function migrates all your VM´s to other nodes in the cluster based on available Host memory
   Evacuate-SCVMHost -VMHost hyp02 -HostGroup DC01
Niklas Akerlund/Lumagate 2012-11-25
function Evacuate-SCVMHost
        # What VMHost you want to set to maintmode

        # In what hostgroup the host resides 
    # Get The cluster and disable the dynamic optimization during evac 
    $HostGroup = Get-SCVMHostGroup $HostGroup
    $HostGroup | Get-SCDynamicOptimizationConfiguration | Set-SCDynamicOptimizationConfiguration -ManualMode 
    $VMHost = Get-VMHost $VMHost
    # Evacuate the host
    $VMs = $VMHost | Get-VM
    foreach ($VM in $VMs){
        # Find the most apropriate Host in cluster for each VM
       $VMHostTarget = Get-SCVMHostCluster -VMHostGroup $HostGroup | Get-SCVMHost | where {$_.ComputerName -ne $VMHost.ComputerName} | Sort-Object AvailableMemory -Descending | Select-Object -First 1
       Move-SCVirtualMachine -VM $VM -VMHost $VMHostTarget  
    # Set the host in maintmode
    Disable-VMHost -VMHost $VMHost -MoveWithinCluster
    # Enable dynamic optimization
    $HostGroup | Get-SCDynamicOptimizationConfiguration | Set-SCDynamicOptimizationConfiguration -AutomaticMode
Categories: Hyper-V, Powershell, SCVMM, Virtualization Tags: