Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Of all the things that sometimes drill me is having to do a web search for PowerShell cmdlets, and seems too often I am just looking for how to use a cmdlet, and after 10 pages of text, you ask yourself, how do I use this cmdlet again? :)
So it's my hope to promote solutions on my blogs, and allow others to use (or plagiarize them) as needed.
Today? The creation of VMs in PowerShell. This is a 2 part solution which uses a batch file to call a PowerShell script. Why? Because I love variables, and once and done solutions.
Here's how:
Step 1: Create a newvm.ps1 file
Here's the PowerShell:
Param(
[Parameter(Mandatory=$true)][string]$vmHost,
[Parameter(Mandatory=$true)][string]$vmName,
[Parameter(Mandatory=$true)][string]$vmPath,
[Parameter(Mandatory=$true)][string]$vmSwitch,
[Parameter(Mandatory=$true)][long]$vmMemoryStartup,
[Parameter(Mandatory=$true)][long]$vmNewDiskSize,
[Parameter(Mandatory=$true)][string]$vmMACEnd)
New-VM -ComputerName $vmhost -Name $vmName -Generation 2 -Path $vmPath\$vmName -SwitchName $vmSwitch -BootDevice NetworkAdapter -MemoryStartupBytes $vmMemoryStartup -NewVHDPath $vmPath\$vmname\$vmName.vhdx -NewVHDSizeBytes $vmNewDiskSize
Set-VMNetworkAdapter -ComputerName $vmHost -vmName $vmName -StaticMacAddress $vmMACEnd
Add-VMDvdDrive -VMName $vmName
Step 2: Create the batch file (newvm.bat)
Assumptions
- HOST1 is your Hyper-V host
- You are creating VMs DC01 and DC02
- The switch you are using is called MySwitch and that it is already created.
- You will be storing the VMs themselves in D:\VM (and then a folder called DC01 and DC02, respectively).
- You will be setting status MAC assignments ending in 01 and 02, respectively
@echo off
powershell -file .\newvm.ps1 -vmhost "HOST2" -vmName "DC01" -vmPath "D:\VM" -vmSwitch "MySwitch" -vmMemoryStartup 1073741824 -vmNewDiskSize 42949672960 -vmMACEnd CC:CC:CC:CC:CC:01"
powershell -file .\newvm.ps1 -vmhost "HOST2" -vmName "DC02" -vmPath "D:\VM" -vmSwitch "MySwitch" -vmMemoryStartup 1073741824 -vmNewDiskSize 42949672960 -vmMACEnd "CC:CC:CC:CC:CC:02"
Clarifications on Memory Startup and Disk Space:
This is calculated in bytes - so for example: 1GB is 1024*1024*1024. 2GB would be 1024*1024*1024*2. Below is a quick list:
Memory:
1GB: 1073741824
2GB: 2147483648
4GB: 4294967296
8GB: 8589934592
Disk:
40GB: 42949672960
300GB: 322122547200
Hope you did find this useful and it helps accelerate your productivity in PowerShell.
-- If you like my blogs, please share it on social media, rate it, and/or leave a comment. --