Copy to mounted VHD with PowerShell for automated Hyper-V Provisioning – Part II

While I initially tried to get the Powershell Mount-VHD cmdlet working – I gave up as it didn’t seem to exist (despite obvious documentation:

I was using a Server 2012 DS for testing purposes, but as I was just working on the drive letter side of things – I had yet to install the Hyper-V role. Turns out that Mount-VHD is exactly what I need to get the driveletter of a VHD and requires Hyper-V to be installed. The last example on the Microsoft Site gives you all you need to know:

Mount-VHD –Path c:\test\testvhdx –PassThru | Get-Disk | Get-Partition | Get-Volume

With a little modification we can ensure that the System Reserved partition does not get in the way:

Mount-VHD -Path PATH -PassThru | Get-Disk | Get-Partition | Get-Volume | Where-Object {$_.FileSystemLabel -ne 'System Reserved'}

This is what you will get after mounting using the above command:


You can then select the driveletter column to get what you need:

Mount-VHD -Path PATH -PassThru | Get-Disk | Get-Partition | Get-Volume | Where-Object {$_.FileSystemLabel -ne 'System Reserved'} | Select DriveLetter

Much more simple than my previous attempt!


Copy to mounted VHD with PowerShell for automated Hyper-V Provisioning

I have been working on an automated provisioning script for Hyper-V and have been annoyed that there is no way to get the associated drive letter for a mounted VHD based on the VHD path. I have read a few posts from around the net for older versions of PowerShell but on Server 2012 they do not seem to work.

At this point, I have given up trying to find a way to get a unique drive letter, and instead just get the drive letters for any attached VHD. The script I am working on will only continue if there is only one VHD attached. This is a requirement as if there were multiple VHDs attached, I do not know how I can identify which drive letter is assigned to which VHD.

The goal is to have the VHD mounted, and then have a BAT script generated containing IP address configuration information, which, once unmounted and used in my main provisioning script will allow the user to ‘automatically’ set the VM IP address. The BAT (Or PowerShell – haven’t worked out if the security settings will allow for a PowerShell script to run on start-up) script will then run on the first boot of the VM and set the correct IP address, gateway and so on.


In the example below (which I will be updating from time to time) I have created a script that will first ensure that there are no more than one VHDs mounted. It will then create/check a lockfile before continuing. If the lockfile is unlocked, it will echo “Copying to VHD”. At this point it is just an echo of text and continue. I have yet to work out the BAT format for setting the IP correctly.

I will be aiming to have the BAT file configured before it hits the copy stage. This will probably just be another function that creates the file. Then in the copyToVhd function, it will mount the associated VHD, copy the BAT file to a start-up folder (or something of the sort) and then unmount the VHD. All with a fairly decent level of protection against having the copyToVhd function being run by different people at the exact same time (which would make it impossible to copy the BAT file to the correct VHD)

When I have some more time to work on it, Ill probably be more flexible with the first check and have it as a while loop to allow for cases where the VHD may not have been detached from another script in progress.

Anyway, this is what I have so far: *Forgive my total and utter messiness – I have no formal PowerShell training, and have only been playing with it for a week!


#Function to get mounted VHD drive letters. Thanks internet for the example.
function get-mountedvhdDrive {            
$disks = Get-CimInstance -ClassName Win32_DiskDrive | where Caption -eq "Microsoft Virtual Disk"            
foreach ($disk in $disks){            
 $vols = Get-CimAssociatedInstance -CimInstance $disk -ResultClassName Win32_DiskPartition             
 foreach ($vol in $vols){            
   Get-CimAssociatedInstance -CimInstance $vol -ResultClassName Win32_LogicalDisk |            
   where VolumeName -ne 'System Reserved'            

#Get just the drive letters (Used to ensure only one device)
$vhdletter = (get-mountedvhdDrive | select DeviceID )

#Present Results
echo "The following VHDs are attached to the system:"

#Ensure there is only one VHD atached - (Saftey measure)
if ($vhdletter.length -gt 1) {Write-Host  "Cannot Automatically Assign IP Address - Multiple VHDs attached. Sorry but I cannot help you anymore." -foregroundcolor red; Write-Host ""; break}
else {Write-Host "Only one VHD attached - Nice and safe. Moving on." -foregroundcolor green}

#Lock file used globally
$lockfile = "C:\lock.txt"

#Function to check if lockfile is locked.
function waitForIt 
#If lock file does not already exist, create. Wait just in case another script is running.
Start-Sleep -m (Get-Random -minimum 1500 -maximum 4000)
If (!(Test-Path $lockfile  -PathType Leaf)) 
    Write-Host "Lock File Does not Exist, Creating"
    New-Item $lockfile -type file
	#Set to 0 to allow script to continue
	echo 0 >>$lockfile

#Continue if lock file exists
ElseIf (Test-Path $lockfile -PathType Leaf)

#Echo "Please Wait" until lock file returns 0 (Free)
$busy = (Get-Content $lockfile)[0]
$crazy = (Get-Random -minimum 10000 -maximum 50000)
Write-Host "Please Wait";
Write-Host ""; 
do {Write-Host $crazy" bananas remaining." -foregroundcolor yellow; $crazy = ($crazy - 500); Write-Host ""; $busy = (Get-Content $lockfile); Start-Sleep -m 1000}
while ($busy -ne 0)

#Added step for additional randomness.
Read-Host "Enter to Continue"

function copyToVhd
	#This will lock the lockfile, mount the VHD, copy a file into the VHD, unmount the VHD and then unlock the lock file.
	#Clear lockfile as we are only checking the first 'item' in the array.
	Clear-Content $lockfile 
	#Lock the lockfile
	echo 1 >>$lockfile

	#Script to copy to VHD ETC coming soon. Sample echo for now.
	echo "Copying to VHD"
	Read-Host "Enter to Continue"
	echo "Copy complete"

	#After script complete, unlock lock file
	#Clear lockfile
	Clear-Content $lockfile 
	echo 0 >>$lockfile


If anyone has any idea on how to get a drive letter based on the mounted VHD I would be super happy! This would mean the lock file wouldn’t be necessary, as I could identify which drive letter to copy to, and unmount based on that also.


I am still alive.

Moving to Australia

So, the time has come to leave Japan. I really planned on staying here a long time but – due to a certain opportunity and various other ‘things’ we have begun to leave Japan. I am really going to miss living here, especially the gigabit unlimited fibre internet. I will also miss Amazon Japan – same day delivery is awesome. Alas, these are just trivial matters but I will miss them none-the-less.

So – we are selling everything. I have a list of stuff here: If there is something not on the list, and you think it should be – it probably is. I buy a lot of stuff I don’t really need, but is nice to have.

I will be writing up another page on what we are doing to prepare for our move to Australia. You may find it useful if you find yourself in the same situation. You can check it here:

Oh, I am also selling the car. It is a shame that it would cost ~$6000 to have it shipped to Australia. We cannot afford this and so must sell. Even though I was told the car “holds its value”, the most I have been offered by car companies is 1500000 yen. This is pretty sad considering its only a year and a half old, has less than 20,000km on it and cost us initially 2800000. Still, without sacrifice there can be no progress 🙂


Knob of the month.

Brendyn Layne is the knob of the month.

Howto: Water Drop Photography

I had been trying to replicate a photo I saw online recently of a bowl of jellybeans though water drops. Not having a bowl of jellybeans lying around – I cheated. I loaded a picture of jellybeans onto my iPad and used that as a backdrop. Here are a couple of shots:



The main issue I had was getting the water to form beads. This time round I applied Glaco (Similar to RainX) to a different sheet of glass. The water beaded up instantly. This time I used some candles as the backdrop instead of the jellybeans.

 To take photos like this you don’t need much. I made a basic frame using knex, and then placed a clean piece of glass over the top. It did take a while to get the glass clean enough, trust me – its worth spending alot of time getting it perfectly clean. Dust specs and watermarks show up very clearly. I recommend using newspaper to clean and polish the glass.

I used a spray bottle to make the water drops. If you want more control over the layout, try using an eyedropper.

At the bottom of my frame I set up a grid of red and yellow/white candles. I tried a few different patterns, but this looked the most appealing.

I was using macro tubes for the first few photos. After removing them I noticed that I could still focus close enough to get a good shot. So, use them if you need to but check to see if you can achieve the effect without them first.

You will also need a good tripod. I have a Manfrotto that allows you to slide the center column out sideways, making it very easy to aim the camera straight down. Getting the camera position just right is very important if you are using macro tubes. Just a centimeter or so too high/low will put your image out of focus. I used a coin to help getting the camera in focus.

Focusing with a coin.

Single drop with unlit candles.

Single drop with lit candles.

Multiple drops.

Multiple drops with additional light source.

You may also want to adjust the aperture to control the bokeh.

© 2021 Chris's Blog

Theme by Anders NorénUp ↑