Automatically deploy Hyper-V machines with PowerShell
Before we can start with PowerShell, you will have to install Windows 10 or a Windows Server in a Hyper-V environment. We will be using this image to create new VMs. It is important to note, that this will make it possible to have one default image that your are using for every environment. You will also have to keep this image up to date. We will also use certain Hyper-V machine sizes, which makes it easier if you want to provide a service, like server hosting, to customers. This makes handling and planning of these environments easier.
Also make sure that you shutdown the image in a generalized state:
If you want to try this on your Windows 10 Machine, you will need to install Hyper-V.
First, we need to create a lot of variables. And I mean A LOT. There are things like $environmentName, $type, $OS that I define so that I see what kind of machine that is without checking a document. I also want the last 3 digits of the IP to be part of the name.
And then there are the paths. Your will need to define this!
Path where the VM is gonna be stored
Path where the Parent OS, which we will use to create the machines, is stored
Path where the VHD with the OS will be stored
Path where the additional D drive is stored
Also don’t forget to change $VMHost, because this needs to be your Hyper-V.
Next we build the credentials to log onto the machine.
Because I want to provide set systems, I will define certain VM sizes which a customer can choose from.
In the next step we will create the VM. About time I would say! In the first try/catch we will copy the parent OS HDD to our directory. In the second try/catch we are creating the VM. And in the third one, we are updating some settings. During the VM creating and the updating of settings, we are using the VM sizes defined in our switch block above.
Now we can update the VM again and attach a second HDD.
Finally we can start the VM!
Finally we will set the IP of the new VM. For this, we need the machine to be powered on, but there is now way to tell if the OS is already up and running. That’s why we are using do/while and a little bit of trickery. After changing the IP we will restart the machine and you can log onto a brand new VM.
And we are done. You can find the script below or in the Github repo.