{"id":1005,"date":"2020-06-09T18:28:08","date_gmt":"2020-06-09T17:28:08","guid":{"rendered":"http:\/\/ihni.uk\/index.php\/2020\/06\/09\/powershell-single-or-bulk-add-new-vms\/"},"modified":"2020-06-09T18:28:08","modified_gmt":"2020-06-09T17:28:08","slug":"powershell-single-or-bulk-add-new-vms","status":"publish","type":"post","link":"https:\/\/ihni.uk\/?p=1005","title":{"rendered":"Powershell &#8211; Single or Bulk add new HyperV VMs"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">I am iniating a project where I am going to have to setup potentially 2-300 new VMs to upgrade existing infrastructure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They&#8217;re all based on Hyper V so it makes sense to script this so it can be quickly deployed either one at a time or in bulk with the ISOs attached and ready to go!<!--more--><\/p>\n<p>So this would be better supported by a VHDX with a SYSPrep already created and a working OS in there so that the machine could be quickly stood up, patched and ready to roll!<br \/>That&#8217;ll be in a later itteration.<\/p>\n<p>Onward&#8230; with the code!\u00a0<\/p>\n<pre>[powershell]# Script to Create and Deploy a HyperV Guest from onscreen prompts or from CSV.\n# CSV format: \n# name,vcpu,mem,memtype,newvhd,vhdtype,switchname,vlanid,vmisopath,newvhdpath,path,generation\n\nPush-Location (Split-Path -path $MyInvocation.MyCommand.Definition -Parent)\n\n$manual = New-Object System.Management.Automation.Host.ChoiceDescription '&amp;amp;amp;amp;Manual', 'Create Manually'\n$csv = New-Object System.Management.Automation.Host.ChoiceDescription '&amp;amp;amp;amp;CSV', 'Create from CSV'\n$options = [System.Management.Automation.Host.ChoiceDescription[]]($manual, $CSV)\n$title = 'HyperV Guest Creation'\n$message = 'Hello, would you like a VM manually or from a CSV?'\n$result = $host.ui.PromptForChoice($title, $message, $options, 0)\n\nswitch ($result)\n{\n    0 { 'Create Manually'\n        $name = Read-Host -Prompt &quot;New VM Name&quot;\n        $vcpu = Read-Host &quot;How Many CPUs (Numeral Only)&quot;\n        $mem = Read-Host -Prompt &quot;Memory Required (GB) (Numeral Only)&quot;\n        $memType = Read-Host &quot;Dynamic Memory?(Y\/N)&quot;\n        $NewVHD = Read-Host -Prompt &quot;Disk Size (GB) (Numeral Only)&quot;\n        $vhdType = Read-Host &quot;Dynamic VHD?(Y\/N)&quot;\n        $SwitchName = Read-Host -Prompt &quot;Switch Name&quot;\n        $vLANid = Read-Host -Prompt &quot;VLAN (Numeral Only)&quot;\n        $vmISOPath = &quot;C:\\ClusterStorage\\Volume1\\ISO\\SW_DVD9_Win_Server_STD_CORE_2019_1909.4_64Bit_English_DC_STD_MLF_X22-29333.iso&quot;\n\n\n        $NewVHDPath = &quot;C:\\ClusterStorage\\Volume1\\Virtual Hard Disks\\&quot;+$name+&quot;\\&quot;+$name+&quot;-OSDisk.vhdx&quot;\n        $Path = &quot;C:\\ClusterStorage\\Volume1\\Virtual Machines\\&quot;\n        $Generation = 2\n\n        Write-Host &quot;Confirm Below is correct:&quot; -foregroundcolor black -BackgroundColor Yellow\n        Write-Host &quot;Name          : $Name&quot;\n        Write-Host &quot;CPU           : $vcpu&quot;\n        Write-Host &quot;Memory        : $mem GB. Dynamic = $memtype&quot; \n        Write-Host &quot;Switch Name   : $Switchname&quot;\n        Write-Host &quot;VLAN          : $vlanID&quot;\n        Write-Host &quot;Disk Size     : $newVHD GB. Dynamic = $vhdType&quot;\n        Write-Host &quot;ISO           : `n $vmisopath&quot;\n        Write-Host &quot;Generation    : $generation&quot;\n        Write-Host &quot;VM Path       : `n $path&quot;\n        Write-Host &quot;VHD Path      : `n $newvhdpath&quot;\n\n\n        Pause\n\n        # Create VM with options Above.\n        New-VM -Name $Name -Path $Path -Generation $Generation\n        # Set Amount of CPU\n        Set-VMProcessor -VMname $name -Count $vcpu\n        # Set Memory and Specify Fixed or Dynamic\n        If($memType -eq 'N'){\n            #Convert RAM to Bytes\n            [int64]$mem = 1GB*$mem\n\n            Set-VMMemory -VMName $name -StartupBytes $mem -DynamicMemoryEnabled $false}\n        Else{\n            #Convert RAM to Bytes\n            [int64]$mem = 1GB*$mem\n\n            Set-VMMemory -VMName $name -StartupBytes $mem -DynamicMemoryEnabled $True}\n        # Set VM Network Details\n        Connect-VMNetworkAdapter -VMName $name -SwitchName $SwitchName\n        Set-VMNetworkAdapterVlan -VMName $name -Access -VlanId $vLANid\n\n        # Set Virtual Disk Drives\n        If($vhdType -eq 'N'){\n            #Convert Size to Bytes\n            [int64]$newVHD = 1GB*$NewVHD\n            New-VHD -path $NewVHDPath -SizeBytes $newVHD -fixed}\n        Else{\n            #Convert Size to Bytes\n            [int64]$newVHD = 1GB*$NewVHD\n            New-VHD -path $NewVHDPath -SizeBytes $newVHD -dynamic}\n        #Attach to VM\n        Add-VMHardDiskDrive -VMName $name -path $NewVHDPath\n\n        # Set Boot Media\n        Add-VMDvdDrive -VMName $Name -Path $vmISOPath\n        Set-VMDvdDrive -VMName $name -Path $vmISOPath\n\n        # Set 1st Boot Device to DVD\n        $vm = Get-VM -Name $name\n        $firmware = Get-VMFirmware -VM $vm\n        $bootorder = $firmware.BootOrder\n        foreach ($bootdev in $bootorder) {\n            if ($bootdev.FirmwarePath.Contains(&quot;Scsi(0,1)&quot;)) {\n                Set-VMFirmware -FirstBootDevice $bootdev -VM $vm\n            }\n        }\n\n        # Start VM\n        Start-VM -VMName $name}\n\n    1 { 'Create from CSV'\n        $CSV = Import-CSV C:\\Users\\adminno\\Documents\\NewServers.csv\n        ForEach($guest in $csv){\n            $name = $guest.name\n            $vcpu = $guest.vcpu\n            $mem = $guest.mem\n            $memType = $guest.memtype\n            $NewVHD = $guest.newVHD\n            $vhdType = $guest.vhdType\n            $SwitchName = $guest.switchname\n            $vLANid = $guest.vlanid\n            $vmISOPath = $guest.vmISOpath\n            $NewVHDPath = $guest.NewVHDPath+$name+&quot;\\&quot;+$name+&quot;-OSDisk.vhdx&quot;\n            $Path = $guest.path\n            $Generation = $guest.generation\n\n            Write-Host &quot;Confirm Below is correct:&quot; -foregroundcolor black -BackgroundColor Yellow\n            Write-Host &quot;Name          : $Name&quot;\n            Write-Host &quot;CPU           : $vcpu&quot;\n            Write-Host &quot;Memory        : $mem GB. Dynamic = $memtype&quot; \n            Write-Host &quot;Switch Name   : $Switchname&quot;\n            Write-Host &quot;VLAN          : $vlanID&quot;\n            Write-Host &quot;Disk Size     : $newVHD GB. Dynamic = $vhdType&quot;\n            Write-Host &quot;ISO           : `n $vmisopath&quot;\n            Write-Host &quot;Generation    : $generation&quot;\n            Write-Host &quot;VM Path       : `n $path&quot;\n            Write-Host &quot;VHD Path      : `n $newvhdpath&quot;\n\n            Pause\n\n            # Create VM with options Above.\n            New-VM -Name $Name -Path $Path -Generation $Generation\n            # Set Amount of CPU\n            Set-VMProcessor -VMname $name -Count $vcpu\n            # Set Memory and Specify Fixed or Dynamic\n            If($memType -eq 'N'){\n                #Convert RAM to Bytes\n                [int64]$mem = 1GB*$mem\n\n                Set-VMMemory -VMName $name -StartupBytes $mem -DynamicMemoryEnabled $false}\n            Else{\n                #Convert RAM to Bytes\n                [int64]$mem = 1GB*$mem\n\n                Set-VMMemory -VMName $name -StartupBytes $mem -DynamicMemoryEnabled $True}\n            # Set VM Network Details\n            Connect-VMNetworkAdapter -VMName $name -SwitchName $SwitchName\n            Set-VMNetworkAdapterVlan -VMName $name -Access -VlanId $vLANid\n\n            # Set Virtual Disk Drives\n            If($vhdType -eq 'N'){\n                #Convert Size to Bytes\n                [int64]$newVHD = 1GB*$NewVHD\n                New-VHD -path $NewVHDPath -SizeBytes $newVHD -fixed}\n            Else{\n                #Convert Size to Bytes\n                [int64]$newVHD = 1GB*$NewVHD\n                New-VHD -path $NewVHDPath -SizeBytes $newVHD -dynamic}\n            #Attach to VM\n            Add-VMHardDiskDrive -VMName $name -path $NewVHDPath\n\n            # Set Boot Media\n            Add-VMDvdDrive -VMName $Name -Path $vmISOPath\n            Set-VMDvdDrive -VMName $name -Path $vmISOPath\n\n            # Set 1st Boot Device to DVD\n            $vm = Get-VM -Name $name\n            $firmware = Get-VMFirmware -VM $vm\n            $bootorder = $firmware.BootOrder\n            foreach ($bootdev in $bootorder) {\n                if ($bootdev.FirmwarePath.Contains(&quot;Scsi(0,1)&quot;)) {\n                    Set-VMFirmware -FirstBootDevice $bootdev -VM $vm\n                }\n            }\n\n            # Start VM\n            Start-VM -VMName $name}\n            }\n}\n\n[\/powershell]<\/pre>\n\n\n\n\n","protected":false},"excerpt":{"rendered":"<p>I am iniating a project where I am going to have to setup potentially 2-300&hellip;<\/p>\n","protected":false},"author":1,"featured_media":988,"comment_status":"open","ping_status":"open","sticky":false,"template":"template-page-builder-no-sidebar.php","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[8,19,11],"tags":[],"class_list":["post-1005","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-hyperv","category-powershell","category-scripts"],"jetpack_featured_media_url":"https:\/\/ihni.uk\/wp-content\/uploads\/2020\/02\/Powershell.png","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/posts\/1005","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ihni.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1005"}],"version-history":[{"count":0,"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/posts\/1005\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ihni.uk\/index.php?rest_route=\/wp\/v2\/media\/988"}],"wp:attachment":[{"href":"https:\/\/ihni.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1005"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ihni.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1005"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ihni.uk\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1005"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}