Test Hyper-V VHD Folders with PowerShell

I’ve recently added a USB 3.0 Express Card adapter to my laptop to provide USB 3.0 functionality. The added performance is very useful in my Hyper-V setup. However, I am running into a glitch that I have yet to figure out where the external drives (the Express card has 2 ports) are still attached and recognized, but the file system is wonky. I can see most of the folders, and files but not really. This is a problem when I fire up a Hyper-V virtual machine with a VHD in one of these folders. Even though I can run a DIR command and see the file, it really isn’t there. So I threw together a little function to add to my Hyper-V workflow module to validate folders with VHD and VHDX files.

My virtual machines are spread out among a number of drives. I don’t necessarily need to validate every VHD file, but I would like to know that the paths exist. Now, I could simply pass my list of paths to Test-Path.

PS C:\> "G:\VHDs","F:\VHD","D:\VHD","C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks" | Test-Path

But my little glitch can lead to a false positive. So I need to take an extra step and validate one of the VHD/VHDX files using the Test-VHD cmdlet. Here’s my function.

#requires -version 3.0

Function Test-VHDPath {

Param (
[ValidateScript({Test-Path $_})]
#paths to my virtual hard disks for Hyper-V virtual machines
[string[]]$paths = @("G:\VHDs","F:\VHD","D:\VHD","C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks")

Write-Verbose "Starting $($MyInvocation.mycommand)"

foreach ($path in $paths) {
  Try {
    #grab the first VHD\VHDX file and test it. No guarantee other files are OK
    #but at least I know the path has been verified.
    Write-Verbose "Validating $path"
    dir $path\*.vhd,*.vhdx | Select -first 1 | Test-VHD -ErrorAction Stop | out-null
  Catch {
    Write-Error "Failed to validate VHD\VHDX files in $Path. $_.Exception.Message"

#if no errors were found then return a simple True
Write-Verbose "No problems found with VHD paths"
Write $True

} #end function

The function gets the first VHD or VHDX file in each folder and tests it. If the test fails, Test-VHD throws an exception which I catch and then bail out. Otherwise, if there are no errors, the function writes $True to the pipeline. Otherwise, I’ll get an exception.

test-vhdpathBut now I have a tool to quickly verify paths before I start trying to launch virtual machines.

If you’d like to learn more about Test-VHD, take a look at my article on the Altaro Hyper-V blog. If you want to try out my function, you should be able to toggle to plain code and copy and paste.


About the Author

PowerShell.org Announcer

This is the official account for PowerShell.org and sponsor announcements.