PowerShell Script to Register a bunch of Virtual Machines [Virtual PC]
When I was getting ready to head out to TechEd this week I copied a bunch of my Windows Virtual PC virtual machines onto a USB disk. 60 of them to be precise. But then I had the problem of how to get them all registered.
Sure, you can register a virtual machine with Windows Virtual PC by just double clicking on the .VMC file for the virtual machine – but this also starts the virtual machine. I did not want to have to start (and stop) all 60 virtual machines just to get them registered. So I threw together this little PowerShell script to do the job for me:
# Switch to using Single-Threaded Apartment model - needed by WinForms
if([Threading.Thread]::CurrentThread.ApartmentState -ne "STA")
{
PowerShell -NoProfile -STA -File $myInvocation.MyCommand.Definition
return
}
# Make new folder browse dialog - and display it
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.folderbrowserdialog
$OpenFileDialog.Description = "Select a folder to register virtual machines from."
$OpenFileDialog.ShowDialog() | Out-Null
# Only move on if the user actually selected a folder
if ($OpenFileDialog.SelectedPath)
{
# Find all .VMC files under the directory selected by the user
$files = get-childitem $OpenFileDialog.SelectedPath -recurse | where {$_.extension -eq ".vmc"}
# Get the VPC object
$vpc = new-object –com VirtualPC.Application –Strict
# Go through each of the .VMC files and register them
Foreach ($file in $files)
{
$vpc.RegisterVirtualMachine($file.Name,$file.DirectoryName) | Out-Null
}
}
When you run this script – you will be presented with a folder selection dialog. Once you have selected a folder the script will then look for – and register – all .VMC files that exist underneath that folder. Very handy!
Cheers,
Ben