I use Windows 8 or Windows Server 2012 R2 on most of my local workstations between home and work. In order to conserve memory, I turn my Hypver-V lab environments on and off as I need them. Given that my smallest environment is a grouping of five virtual machines (VMs), I quickly got tired of all of the clicks necessary to start up all of the machines, in order, or save them all when I was done.
To solve this problem, I wrote the below functions in PowerShell and added them to my Windows PowerShell Profile.aspx). These functions take advantage of the Hyper-V module, available in Windows 8 and above or Windows 2012 and above. There are over 160 Cmdlets to pick from. In this post we will only demonstrate two, Start-VM and Save-VM.
Functions
It is important to run the Hyper-V cmdlets in a PowerShell session that is running “As Administrator”.
function Start-MyVMs
{
#start AD VM
Start-VM 'v-hammer-ad';
#start SQL VMs
$SqlVms = @('v-hammer-01','v-hammer-02',
'v-hammer-03','v-hammer-04');
$jobs = @();
foreach($VM in $SqlVms)
{
$args = @($VM);
$jobs += Start-Job -ScriptBlock { Start-VM $args[0] }
-ArgumentList $args;
}
$jobs | Wait-Job | Receive-Job | Remove-Job;
}
function Save-MyVMs { #Save SQL VMs $SqlVms = @('v-hammer-01','v-hammer-02', 'v-hammer-03','v-hammer-04'); $jobs = @(); foreach($VM in $SqlVms) { $args = @($VM); $jobs += Start-Job -ScriptBlock { Save-VM $args[0] }-ArgumentList $args; }$jobs | Wait-Job | Receive-Job | Remove-Job; #Save AD VM Save-VM 'v-hammer-ad'; }
Quick overview
In this particular lab environment I have an Active Directory server with four VMs joined to the domain. This is an environment that I use to run tests on a SQL Server Availability Group configuration.
I’ve decided that I want my VMs to start and be saved with the AD VM online at all times. I also don’t want to have to wait for each one to start or save individually. To accomplish these goals I’ve used the Start-VM and Save-VM cmdlets for V-HAMMER-AD by themselves. I then used the Start-Job cmdlet to spawn asynchronous jobs. These jobs run in parallel and bring the remaining SQL VMs up as fast as my hardware will allow. Then I wait for the jobs to complete (Wait-Job), output the error or information messages to my console (Receive-Job), and dispose of the jobs (Remove-Job).
Since these have been added to my profile, every time I open a PowerShell console window the functions are loaded and a single cmdlet manages my lab environment’s state.
Leave a Reply