Shrink HyperV virtual hard disk Win8 / Win2012 with PowerShell

May 13th, 2012 No comments

I read this post by Ben (Virtual PC Guy) Armstrong about shrinking a virtual hard disk and thought this should be done with powershell.

So first I have to shrink the partition inside the VM, for this I use the New-CIMSession (instead of powershell remoting and such) and then I shut down the VM and shrink the VHDx file, As someone correctly noted, this shrink of the virtual disk file is only possible when using the new VHDx format.

The VM is part of the same domain as the hyper-V server from which I am running the script, this made it easier to make a cim connection. The VM is also a Win 8 beta cause I need the latest win framework with powershell 3.

As you can see, the disk in my VM is 60 GB and I want to shrink it to the minimum size * 20% (so i get at least some space left ;-)

Now I will run my little script and here is what that looks like

# vNiklas Masterblaster shrink
#
# Niklas Akerlund / 2012-05-13

$VM = "Shrink8"

$cim = New-CimSession $VM

$partitionC = Get-Partition -CimSession $cim -DriveLetter C

$newSize = ($partitionC | Get-PartitionSupportedSize).SizeMin*1.20

Resize-Partition -PartitionNumber $partitionC.PartitionNumber -DiskNumber $partitionC.DiskNumber -Size $newSize -CimSession $cim

Get-Volume C -CimSession $cim

$VM = Get-VM $VM

Stop-VM $VM

$hdd = $VM | Get-VMHardDiskDrive

Resize-VHD -Path $hdd.Path -ToMinimumSize

Start-VM $VM

And here you can see the result, a quite simple solution..

Good luck in your shrinking :-)

Update:  I totally missed that Ben had done a post about doing it with powershell, just after his other post when i was making this post… At least my solution show how to connect to a VM with CIM :-)

 

Bare metal deploy with SCVMM 2012 fail with error 800b0109 in WinPE

May 11th, 2012 No comments

Today I was at a customer and upgraded their VMM 2012 from RC to RTM. We got an issue when trying to run a bare metal deploy after the upgrade, at first we did not understand what was causing the error, but my suspicion was on the winpe that was published by VMM in the WDS PXE.

Here is the error in the VMM Console also

And then i used PowerShell to update the VMM WinPE that resides in the WDS, this because their environment had new HP blades and i needed to add a nic driver. If you do not need to add anything to the winpe you can right click on the VMM console and the PXE  and you find a selection “Update WinPE Image” this will use an image from the WAIK installed on the VMM Server. Here is the link for the powershell cmdlet that updates the WinPE

The Powershell I ran was as below, I had to run the dism tools with elevated rights, this can be done by right click on the Powershell console and “Run As Administrator”

Import-Module "C:\Program Files\Microsoft System Center 2012\Virtual Machine Manager\bin\psModules\virtualmachinemanager\virtualmachinemanager.psd1"
Get-SCVMMServer localhost
$mountdir = "E:\mount"

$winpeimage = "E:\temp\custom_winpe.wim"

$winpeimagetemp = $winpeimage + ".tmp"

mkdir "E:\mount"

copy $winpeimage $winpeimagetemp

dism /mount-wim /wimfile:$winpeimagetemp /index:1 /mountdir:$mountdir

$path = "E:\temp\drivers\be2nd62.inf" # $driver.sharepath
dism /image:$mountdir /add-driver /driver:$path

Dism /Unmount-Wim /MountDir:$mountdir /Commit

publish-scwindowspe -path $winpeimagetemp

Here is a link to the technet forum where I found another guy having the same issue, whom I helped.

After updating the WinPE we tried to do a new bare metal deploy and this time we had no issues with the certificate.

 

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

PowerCLI report on datastores, overprovision and number of powered on VM´s

May 8th, 2012 No comments

Today I had an reason for running PowerCLI again, the case was to get an quick report on the datastores at a customer, I have made a post about the one-liner that get the number of running VM´s on a datastore. As i described in that post, if your SAN does not support VAAI then you do not want to many VM´s on each datastore because of the SCSI-locking that can occur. This is just an extension of that because we also wanted to check how overprovisioned the datastores was (when using thin provisioning there is a risk that you will fill your datastores as the VM´s fill their vmdk disk´s)

The PowerCLI code looks like this

Get-Datastore | Select Name,@{N="TotalSpaceGB";E={[Math]::Round(($_.ExtensionData.Summary.Capacity)/1GB,0)}},@{N="UsedSpaceGB";E={[Math]::Round(($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.FreeSpace)/1GB,0)}}, @{N="ProvisionedSpaceGB";E={[Math]::Round(($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.FreeSpace + $_.ExtensionData.Summary.Uncommitted)/1GB,0)}},@{N="NumVM";E={@($_ | Get-VM | where {$_.PowerState -eq "PoweredOn"}).Count}} | Sort Name | Export-Csv -Path C:\temp\vmds-datastore.csv -NoTypeInformation -UseCulture

And this is when i have run it on my test system, the difference here is that i removed the Export-CSV to get the output in the console

And here is a simple excel report

 

Categories: Automation, PowerCLI, Virtualization, VMware Tags:

VMware vCloud Director vApp and DRS cluster affinity with PowerCLI

May 3rd, 2012 1 comment

To fully utilize the performance in a vApp in vCloud Director I got the task to create an affinity rule based on the VMs in the vApp. This can be the case for example when you have VMs in an vApp that exchange high loads of data. In our case we have virtual ESXi Servers that have a vsa for shared storage and need good performance when deploying VM´s and storage vMotion etc.

When deploying several vApps from the same template it is not just to run Get-CIVM and then use the VM name returned to run Get-VM for the correlation between the VM in VCD and in vCenter, as you can see in the screendumps these two have the same name but followed with an identifier from vCD in the vSphere Client. This is also described in the vSphere blog.

The fine part is that the MoRef is unique (in the relation one vcd <-> one vcenter) so I can check on that which VMs in the vCenter belongs to the same vCloud Director vApp.

I got the code for the MoRef in this community post.

And here is my script

<#
.Synopsis
   Add an affinity rule for a vCloud Director vAPP
.DESCRIPTION
   This function takes a vApp as parameter and creates an affinity rule for them to keep them together
.EXAMPLE
   Add-CIVAppAffinity -CIVApp Green01
.NOTES
Author: Niklas Akerlund / RTS
Date: 2012-05-03
#>
function Add-CIVAppAffinity
{
    Param
    (
        # Parameter for the vAPP
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $CIVApp,

        # If the rule should apply on a different cluster
        $Cluster = "vCD-Cluster"
    )

	$pod = Get-CIVapp $CIVApp
	if ($pod){
		$PodVMs = Get-CIVM -VApp $pod
		$VMs = @()
		$Cluster = Get-Cluster $Cluster
		Foreach ($PodVM in $PodVMs) {
			$VMname = $PodVM.Name + "*"
			$VM =  Get-VM $VMname | where {$_.ExtensionData.MoRef.Value -eq $PodVM.ExtensionData.VCloudExtension[0].Any[0].VmVimObjectRef.MoRef}
			$VMs +=$VM
		}

		if (!(Get-DrsRule -Cluster $Cluster -Name $pod.Name -ErrorAction SilentlyContinue)){
			New-DrsRule -Name $pod.Name -Cluster $Cluster -KeepTogether $true -VM $VMs
		}else{
			Remove-DrsRule -Rule (Get-DrsRule -Cluster $Cluster -Name $pod.Name) -Confirm:$false
			New-DrsRule -Name $pod.Name -Cluster $Cluster -KeepTogether $true -VM $VMs
		}
	}
}

And when checking the cluster i can see that my DRS affinity rule has been created and the VMs have been migrated to the same host

It is not so extensive but it helps us with the case to create DRS affinity on the VMs in a particular vApp :-) , The Rule is deleted when the vApp is removed, I have an extra check in the script and remove it if it still exist of some reason.

 

Upgrade SCVMM 2012 RC to RTM

April 26th, 2012 No comments

Today I wanted to upgrade my test environment from SC VMM 2012 RC to RTM, as it clearly says in the documentation, this is not supported (unless you are a TAP customer). But do not shout out in anger just until you read the forum, cause you can actually get the db upgrade util even if you weren’t in the TAP program.

Now I was one of the lucky to be in the TAP program so I could download the upgrade binary. First I had to uninstall the VMM Server and the Console, not to forget was to retain the database data (otherwise an upgrade would kind of be meaningless)

When the uninstall was complete, start an elevated prompt and run the tool, if you run UpgradeVMM2012RC.exe /?  you can see what different parameters you can use.

Now I could continue with the installation, but next little problem was to reconnect the old library (my library was not on the default path) so if would choose the existing I would not get my Library correct and I could not change that either in the installation wizard, I selected create a new and got the following error:

This was solved by going to the actual folder and deselect share, without restarting the installation i could continue

Then I was finished installing and the only thing left was to update the VMM agents on the hosts, some people had problems with the need to remove the agent manually but my update was successful

So now I am running the RTM version of SC VMM 2012 :-)

Categories: Hyper-V, SCVMM, Virtualization Tags:

VMware vExpert 2012 award

April 24th, 2012 No comments

 

I am one of the lucky to be awarded as this year VMware vExpert.

As described by the application for VMTN vExpert:

The annual VMware vExpert title is given to individuals who have significantly contributed to the community of VMware users over the past year. The title is awarded to individuals (not employers) for their commitment to sharing their knowledge and passion for VMware technology above and beyond their job requirements.

My focus has been on automation and I try to share my findings in PowerCLI, and of course in other areas too.

Is there a PowerCLI way then I will use it!

Categories: Virtualization, VMware Tags:

Windows Server 2012 (8 beta) Hyper-V enabled inside a VMware Fusion VM

April 23rd, 2012 No comments

I did see that a new version of VMware Fusion has been released as a technology preview and in the release notes I could find that it was possible to run ESXi host-vm with nested 64 bit VM´s in. Of course I had to test and see if I also could get a new Windows 2012 (8 beta) with Hyper-V role enabled and running.

There was some problems that had to be adressed before I got it working, google and help from fellow IT-neerds that had done the same in VMware Workstation solved my problems. And yes it is actually usefull, because I can run a test environment on my Apple laptop to test/demo things :-)

After a clean install i got this error when trying to enable

I had to add these lines to the vmx file inside the VM package

hypervisor.cpuid.v0 = FALSE
vhv.enable = TRUE

I also manually set the preferred virtualization engine to Intel VT-x with EPT

Then i could add the Hyper-V role, but when rebooting i got a nice new kind of blue screen with the error HAL_MEMORY_ALLOCATION.

That was solved with the following line in the vmx file, I have no idea what it means exactly but it has to be something with the memory allocation,

mce.enable = TRUE

Here you can see my screendump on my Hajper-V VM with a Hyper-V VM running inside it :-)

I have not installed VMware tools in the host, this because when enabling the Hyper-V role the OS that is installed becomes an Parent VM, so the tools will not be utilized on the Fusion VM´s hardware.  

 

Categories: Hyper-V, Virtualization, VMware, Win8 Tags:

A PowerShell function for Snapshot reporting in VMM2012

April 16th, 2012 No comments

Hello

I am in the hotel waiting for the MMS 2012 to start so there is time for some automation ;-) . Last week when I was teaching a course one of the attendes said after I showed the custom value function, that he also wanted a similar function for easy in the console check how many snapshots every VM had. In the VMM 2012 console I have not found an built-in function to actually show this.

I have modified the function and created the run script, this is scheduled to run once a hour so you have a updated view of your environment. At least in the Hyper-V for Windows 2008 R2 it is not recommended to use in production.

It is quite easy to create a new custom property that we then will populate,

New-SCCustomProperty -Name "Snapshot Count" -Description "" -AddMember @("VM")

In the GUI there is no way to remove a custom property, I can only remove it from assigned properties. During the course I created an property just for showing and want to get rid of it. Of course there is a powershell cmdlet for that:

Get-SCCustomProperty -Name "Muuuu" | Remove-SCCustomProperty

But now to the part of getting the script to show snapshots (yes I know, in VMM it is called Checkpoints but i refuse to call it that)

First I have the PowerShell function

function Set-CVSnapShot{
<#
.SYNOPSIS
Function to Update custom values for VM´s in VMM 2012
 
.DESCRIPTION
Use this function to  set the custom value Snapshot count
 
.PARAMETER  VMs
Use this parameter to update just that VM´s custom snapshot value
 
.NOTES
Author: Niklas Akerlund / RTS
Date: 2012-04-16
#>
    param (
   [Parameter(Position=0,HelpMessage="A virtual machine pleaze",
    ValueFromPipeline=$True)]
    $VMs = " "
    )
   
  	if ($VMs -eq " "){
    	$VMs = Get-SCVirtualMachine
	}else{
		$VMs = Get-SCVirtualMachine  $VMs
	}

  	$CustomSnapShot = Get-SCCustomProperty -Name "Snapshot Count"
   
	foreach ($VM in $VMs){
		$count = ($VM | Get-SCVMCheckpoint).Count

	    if($count -ne $null){
	        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $CustomSnapShot -Value $count 
	    }else{
	        Set-SCCustomPropertyValue -InputObject $VM -CustomProperty $CustomSnapShot -Value 0 
	    }
   }
}

then I have a very easy script that I task scheduled in my VMM server

# Script to use for scheduled updates of Custom values
#
# Niklas Akerlund / RTS 2012-04-16

ipmo 'C:\Program Files\Microsoft System Center 2012\Virtual Machine Manager\bin\psModules\VirtualMachineManager' | Out-Null

. .\Set-CVSnapshot.ps1
Set-CVSnapshot

And in the VMM Console it looks like this

I will talk to some VMM responsibles at MMS and see if they find an interest and build the view instead of me running it in a sheduled task (as the information is there in the database)

Importing VM´s with PowerShell into Win8 Hyper-V 3.0

April 4th, 2012 No comments

I am working on setting up my lab environment for the M50273 Design course that I am going to teach next week.

The import process is a bit heavy without powershell, cause it is 18 VMs that has to be imported. In a MOC (Microsoft Official Course) the lab setup consists of several VM´s that have base vhd disks and then several tiers of differential disks that need to be connected before import, in every directory there is a .bat file that creates the symlinks, I decided to keep them but run them in a script.

And here you can see the result of running the .bat file

The setup guide for the course says that I should install a Windows 2008 R2 host and then import the VM´s but i want to use Win8 instead, this to be able to run the built-in hyper-v cmdlets and also test if I could run the course VM´s on it.

I did not have this problem (Matthew Dowst) when importing my VM´s to the host but another networking issue occured, when checking the VM settings as you can see in the screen dump that the virtual network adapter is there but not working correctly, a little powershell again helps :-P

And this powershell command that takes the network adapter on the vm and connects it to the Internal switch :

Get-VM *HOU-DPM-E* | Get-VMNetworkAdapter | Connect-VMNetworkAdapter -SwitchName Internal

So then it looks like this in VM settings:

So to automate the import process I created a small script that looks in a directory for VM´s in folders to import, then starts each .bat script to create the symlinks and imports the machine and lastly renames it (cause in the import process it is named REARMEDxxx) and connects the vm to the right network

As you can see, in this script i have not created a function or fancy parameters, that might come in a version 0.2.

# Import VMs for Course
#
# Niklas Akerlund / RTS 2012-04-04

$VMs = Get-Item -Path "E:\Program Files\Microsoft Learning\50273\Drives\*" | Select-Object Name,FullName

foreach ($VM in $VMs){

    if(Get-VM $VM.Name -ErrorAction SilentlyContinue ){
        Write-Host $VM.Name "Already imported"
    }else{
        # Create Symlinks
        $symbat = (Get-Item ($VM.FullName + "\*.bat")).FullName
        & $symbat

        $expfile = (Get-Item ($VM.FullName + "\Virtual Machines\*.exp")).FullName

        Import-VM -Path $expfile 

        Get-VM REA* | Rename-VM -NewName $VM.Name
        Get-VM $VM.Name | Get-VMNetworkAdapter | Connect-VMNetworkAdapter -SwitchName Internal
    }
}

It looks something like this when running

And when it is done I have all my 18 VMs imported and with the right network connected:

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

PHD Virtual Backup and Replication for VMware v5.4

March 31st, 2012 No comments

I have been looking at the PHD Virtual Backup for VMware v5.4 to compare it with other backup vendors..

The new version has some features that is nice, both the replication function and the FLR with iSCSI target can be useful, not to forget the OpenExport and OpenRestore, where you can restore your VM´s to hosts without PHD Virtual Backup sw as they are exported as OVF and can easily be imported into other hosts.

Here is a list of some of the features

  • vSphere Client integration
  • Support for Changed Block Tracking (CBT)
  • Export Virtual Machine Backup
  • Virtual Machine Replication
  • Application Consistent Backup using VSS (Windows only)
  • Application Object level recovery
  • OpenExport & OpenRestore
  • E-mail notification
  • Support for Thin Provisioned Disks
  • Backup Retention and Archiving
  • Distributed Virtual Switch Support
  • Supports all Operating Systems supported by VMware vSphere

The installation of the product is as easy as VMware Data Recovery, you download and extract the OVF and import it into your environment, as I do things with PowerShell/PowerCLI I can use Import-VApp cmdlet

When I then want to install the vSphere Client plugin I can browse the web-service on the appliance and that way get the sw, It is also on the extracted folder you got from the download, but of course you can get the IP adress of the appliance and open an IE window from powershell ;-)

Once installed I need to set up a backup storage and credentials for my vCenter ( If you want you can just enter the ip/fqdn for your ESXi host)

For backup storage i can choose, attached disk/NFS or CIFS share. The most important thing here is that you think this through where you place your backup data, you do not want to put your backups in the same datastores as your VM´s because if you have a SAN-failure you want to be able to restore :-) . One thing I want is to be able to use more than one disk but it is not possible in the PHD VBA in this version.

You can then go ahead and start taking backup. Either you can choose the whole datacenter or cluster or just VM´s, the nice part here is that you can select a Host cluster and exclude the VM´s that you not want to take backup on and when doing like this, new VM´s that are added later are automatically added to the backup job.

Here you can see that when I later add the TESTNEW VM it is automatically added to the backupjob

I can use the functionality quiesce VM to get a consistent snapshot for my backup, then my windows applications (that are VSS aware) will be in a good state to take backup, this is not possible to do with other OS (for example Linux), so think a bit if this is enough for your VM´s, maybe you must have an backup solution that uses an agent inside the VM also?!

For the replication functionality I can add an secondary PHD VBA that is on a DR site and it is configured to use the backup store of the first VBA so I will not need to create more than one VM snapshot for both backup and replication. When i fail-over the VM to the backup-site no more replication will occur and i can then start replicating it back when the primary site is back online.

To do File-level restore you select the VM and the backup date and click create, this will create an iSCSI target that you can connect to and get the data that you want restored. To get application level restore you will have to do the same thing and then connect the database etc in recovery-mode.

To get the OVF´s in OpenExport function you have to install the PHDVB_Exporter sw, PHD recommend you to install it on a physical machine, but it is supported to install in a VM also.

When you have installed it, you have to configure a location for the exported VM´s, also you need to configure where the PHD VBA appliance backups are. When that is done you can continue to create an export job. The export of the backups are set to use the latest backup, this isn not anything I can change in this version.

One thing i wish for in the next release is that they fix the scheduling, as of now when the export job is finished it create a task in the scheduled task manager and there you have to configure that it can run without logged on and when it should run, this should be in the gui of the Export software.

When checking the export directory you can see that the OVF and the vmdk files are there, ready to be imported or backed up by a tape.

Conclusion

What do we need and why is the question when choosing the backup solution. When is Host level backup software enough and when do we need agents in our VM´s? If you decided that Host level backup solution with snapshot technology is enough on your virtualization platform I would say that the reasons for using PHD instead of the VMware Datarecovery are the replication function, File Level restore via iSCSI and the Export to OVF. Also the possibility to set an backup to archive that will exclude that VM backup will be deleted by the retention policy is a powerfull feature for example regulatory reasons. The VMware Data Recovery also require the vCenter and in some cases you maybe do not have that or want to connect to it.

 

Categories: Virtualization, VMware Tags: