none
Need to create a VM in Hyper-V through powershell RRS feed

  • Question

  • Hi,

    We are having small requirement creating a VM automatically through Powershell scripting...

    Can any one suggest whether this can be possible to automatically create a VM in Hyper-V

    Thanks and Regards

    Santosh

    Tuesday, April 16, 2013 6:58 AM

Answers

  • This by no means as easy task however I have found a website which can add you depend on you level of understanding in PS. this was created some time ago so the scripting would be simpler in PS3 however this is a good starting point. hope it helps

    Option Explicit
     
    Dim HyperVServer
    Dim VMName
    Dim WMIService
    Dim VSManagementService
    Dim VSGlobalSettingData
    Dim Result
    Dim Job
    Dim InParam
    Dim OutParam
     
    'Prompt for the Hyper-V Server to use
    HyperVServer = InputBox("Specify the Hyper-V Server to create the virtual machine on:")
     
    'Prompt for the new VM name
    VMName = InputBox("Specify the name for the new virtual machine:")
     
    'Get an instance of the WMI Service in the virtualization namespace.
    Set WMIService = GetObject("winmgmts:\\" & HyperVServer & "\root\virtualization")
     
    'Get the VirtualSystemManagementService object
    Set VSManagementService = WMIService.ExecQuery("SELECT * FROM Msvm_VirtualSystemManagementService").ItemIndex(0)
     
    ' Initialize a new global settings for the VM
    Set VSGlobalSettingData = WMIService.Get("Msvm_VirtualSystemGlobalSettingData").SpawnInstance_()
     
    'Set the VM name
    VSGlobalSettingData.ElementName = VMName
     
    'Setup the input parameter list
    Set InParam = VSManagementService.Methods_("DefineVirtualSystem").InParameters.SpawnInstance_()
    InParam.SystemSettingData = VSGlobalSettingData.GetText_(1) 
     
    'Execute the method and store the results in OutParam
    Set OutParam = VSManagementService.ExecMethod_("DefineVirtualSystem", InParam) 
     
    'Check to see if the job completed synchronously
    if (OutParam.ReturnValue = 0) then
       Wscript.Echo "Virtual machine created."
    elseif (OutParam.ReturnValue <> 4096) then
       Wscript.Echo "Failed to create virtual machine"
    else   
     
       'Get the job object
       set Job = WMIService.Get(OutParam.Job)
     
        'Wait for the job to complete (3 == starting, 4 == running)
       while (Job.JobState = 3) or (Job.JobState = 4)
          Wscript.Echo Job.PercentComplete
          WScript.Sleep(1000)
     
          'Refresh the job object
          set Job = WMIService.Get(OutParam.Job)
       Wend
     
       'Provide details if the job fails (7 == complete)
       if (Job.JobState <> 7) then
          Wscript.Echo "Failed to create virtual machine"
          Wscript.Echo "ErrorCode:" & Job.ErrorCode
          Wscript.Echo "ErrorDescription:" & Job.ErrorDescription
       else
          Wscript.Echo "Virtual machine created."
       end If
    end if

    PowerShell:

    # Prompt for the Hyper-V Server to use
    $HyperVServer = Read-Host "Specify the Hyper-V Server to create the virtual machine on"
     
    # Get name for new VM
    $VMName = Read-Host "Specify the name for the new virtual machine"
     
    # Create new MSVM_VirtualSystemGlobalSettingData object
    $wmiClassString = "\\" + $HyperVServer + "\root\virtualization:Msvm_VirtualSystemGlobalSettingData"
    $wmiClass = [WMIClass]$wmiClassString
    $newVSGlobalSettingData = $wmiClass.CreateInstance()
     
    # wait for the new object to be populated
    while ($newVSGlobalSettingData.psbase.Properties -eq $null) {}
     
    # Set the VM name
    $newVSGlobalSettingData.psbase.Properties.Item("ElementName").value = $VMName
     
    # Get the VirtualSystemManagementService object
    $VSManagementService = gwmi MSVM_VirtualSystemManagementService -namespace "root\virtualization" -computername $HyperVServer
     
    # Create the VM
    $result = $VSManagementService.DefineVirtualSystem($newVSGlobalSettingData.psbase.GetText(1))
     
    #Return success if the return value is "0"
    if ($Result.ReturnValue -eq 0)
       {write-host "Virtual machine created."} 
     
    #If the return value is not "0" or "4096" then the operation failed
    ElseIf ($Result.ReturnValue -ne 4096)
       {write-host "Failed to create virtual machine"}
     
      Else
       {#Get the job object
        $job=[WMI]$Result.job
     
        #Provide updates if the jobstate is "3" (starting) or "4" (running)
        while ($job.JobState -eq 3 -or $job.JobState -eq 4)
          {write-host $job.PercentComplete
           start-sleep 1
     
           #Refresh the job object
           $job=[WMI]$Result.job}
     
         #A jobstate of "7" means success
        if ($job.JobState -eq 7)
           {write-host "Virtual machine created."}
          Else
           {write-host "Failed to create virtual machine"
            write-host "ErrorCode:" $job.ErrorCode
            write-host "ErrorDescription" $job.ErrorDescription}

    http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/05/28/scripting-vm-creation-with-hyper-v.aspx

    Monday, April 22, 2013 4:09 PM
  • and I have found some more upto date info for you.

    This should do it

    http://pshscripts.blogspot.co.uk/2013/01/create-vmps1.html

    1. # Create-VM.ps1 
    2. # Script that creates VMs 
    3. # Version 1.0.0 - 20 Jan 2013 
    4. # See http://tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows-8.html 
    5.  
    6. # First define the Create-VM Function 
    7.  
    8. Function Create-VM { 
    9. #=================================================== 
    10. # Create a New VM 
    11. #=================================================== 
    12.  
    13. # Parameters are Name, Virtual Machine Path, path to reference Vhdx,
    14. # network switch to use, VM Memory, Unattend file, IP address and DNS
    15. # Server to set. Default values are specified in the Param block,
    16. # but these are normally overridden in the call to Create0VM 
    17.  
    18.  
    19. [Cmdletbinding()] 
    20. Param (  
    21.  $Name         = "Server"
    22.  $VmPath       = "C:\v3"
    23.  $ReferenceVHD = "C:\v3\Ref2012.vhdx"
    24.  $Network      = "Internal"
    25.  $VMMemory     = 512mb, 
    26.  $UnattendXML  = "C:\v3\unattend.xml"
    27.  $IPAddr       = '10.0.0.250/24'
    28.  $DnsSvr       = '10.0.0.10' 
    29.  
    30. $Starttime = Get-Date 
    31. Write-Verbose "Starting Create-VM at $Starttime" 
    32. Write-verbose "Creating VM: [$name]" 
    33. Write-verbose "Path to VM : [$VMpath]" 
    34.  
    35. #    Set path to differencing disk location 
    36. $path = "$vmpath\$name.vhdx" 
    37. Write-Verbose "Creating Disk at [$path]" 
    38.  
    39. #    Add a new differencing VHDX, Based on parent parent 
    40. $vmDisk01 = New-VHD –Path $path -Differencing –ParentPath $ReferenceVHD -ErrorAction Stop 
    41. Write-Verbose "Added VM Disk [$VMdisk01], pointing to [ReferenceVHD]" 
    42.  
    43. #    Create a New VM 
    44. $VM = New-VM –Name $name –MemoryStartupBytes $VMMemory –VHDPath $VMDisk01.path -SwitchName $Network -Path $vmPath 
    45. Write-Verbose "VM [$name] created" 
    46.  
    47. # Mount the Disk into the VM 
    48. Mount-DiskImage -ImagePath $path 
    49. $VHDDisk = Get-DiskImage -ImagePath $path | Get-Disk 
    50. $VHDPart = Get-Partition -DiskNumber $VHDDisk.Number 
    51. $VHDVolumeName = [string]$VHDPart.DriveLetter 
    52. $VHDVolume = [string]$VHDPart.DriveLetter + ":" 
    53. Write-verbose "Volume [$Volumename] created in VM [$name]" 
    54.  
    55.  
    56. #    Get Unattended.XML file 
    57. Write-Verbose "Using Unattended XML file [$unattendXML]" 
    58.  
    59. #    Open XML file 
    60. $Xml = [xml](get-content $UnattendXML
    61.  
    62. #    Change ComputerName 
    63. Write-Verbose "Setting VM ComputerName to: [$name]" 
    64. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-Shell-Setup" } | 
    65.  ForEach-Object
    66.    if($_.ComputerName) { 
    67.      $_.ComputerName = $name 
    68.    } 
    69.  
    70. #    Change IP address 
    71. Write-Verbose "Setting VM ComputerName to: [$name]" 
    72. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-TCPIP" } | 
    73.   ForEach-Object
    74.  
    75.     if($_.Interfaces) { 
    76.       $ht='#text' 
    77.       $_.interfaces.interface.unicastIPaddresses.ipaddress.$ht = $IPAddr 
    78.   } 
    79.  
    80. #    Change DNS Server address 
    81. #    Use obscure way to create the #TEXT node 
    82. Write-Verbose "Setting VM DNS address to: [$DNSSvr]" 
    83. $Xml.Unattend.Settings.Component | Where-Object { $_.Name -eq "Microsoft-Windows-DNS-Client" } | 
    84.   ForEach-Object
    85.       if($_.Interfaces) { 
    86.       $ht='#text' 
    87.       $_.Interfaces.Interface.DNSServerSearchOrder.Ipaddress.$ht = $DNSSvr 
    88.   } 
    89.  
    90. #    Save XML File on Mounted VHDX differencing disk 
    91. $xml.Save("$VHDVolume\Unattend.XML"
    92. Write-Verbose "Unattended XML file saved to vhd [$vhdvolume\unattend.xml]" 
    93.  
    94. #    Dismount VHDX  
    95. Write-Verbose "Dismounting disk image: [$Path]" 
    96. Dismount-DiskImage -ImagePath $path 
    97.  
    98. #    Update additional VM settings 
    99. Write-Verbose 'Setting additional VM settings' 
    100. Set-VM -Name $name -DynamicMemory 
    101. Set-VM -Name $name -MemoryMinimumBytes $VMMemory 
    102. Set-VM -Name $name -AutomaticStartAction Nothing 
    103. Set-Vm -Name $name -AutomaticStopAction ShutDown 
    104.  
    105. #    Show what has been created! 
    106. "VM Created:" 
    107. Get-VM -Name $name | fl * 
    108.  
    109. #    Start VM 
    110. Write-verbose "VM [$Name] being started" 
    111. Start-VM -Name $name 
    112.  
    113. #    Now work out and write how long it took to create the VM 
    114. $Finishtime = Get-Date 
    115. Write-Verbose ("Creating VB ($name) took {0} seconds" -f ($FinishTime - $Starttime).totalseconds) 
    116. # End of Create-VM function 
    117.  
    118.  
    119. ####################################################################################################### 
    120. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    121. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    122. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    123.  
    124. # Location of Server 2012 DVD Iso Image 
    125. $iso   = 'c:\Builds\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso' 
    126. # Where we put the reference VHDX 
    127. $ref   = 'c:\v3\Ref2012.vhdx' 
    128. # Path were VMs, VHDXs and unattend.txt files live 
    129. $path  = 'c:\V3' 
    130. # Location of Unattend.xml - first for workstation systems, second for domain joined systems  
    131. $una   = 'c:\V3\UnAttend.xml' 
    132. $unadj = 'c:\V3\UnAttend.dj.xml' 
    133.  
    134. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    135. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    136. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    137. ####################################################################################################### 
    138.  
    139. #   Now run the script to create the VMs as appropriate. 
    140. $Start = Get-Date 
    141. "Create-VM --- Started at: $Start" 
    142.  
    143. #################################################################### 
    144. # Comment out VMs you do NOT want to create then run the entire script 
    145. # To comment out a VM creation, just add a '#" at the start of the line.  
    146. #        Removing the comment line means you want to create that VM.  
    147. #        BE creful!  If you make a mistake, stop the script. Kill any VMs created, then remove the 
    148. #        storage for the VMs.  
    149. ####################################################################################################### 
    150.  
    151. #    Create the DC - NON-domained joined 
    152. # Create-VM -name "DC1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $una -Verbose -IPAddr '10.0.0.10/24' -DNSSvr 10.0.0.10  -VMMemory 1gb 
    153.  
    154. #    Remaining VMs use the domain-join version of unattend.xml 
    155. # Create-VM -name "Srv1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.30/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    156. # Create-VM -name "Srv2"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.31/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    157. # Create-VM -name "Sql1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.20/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
    158. # Create-VM -name "Exch1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.21/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
    159.  
    160. #    DHCP 1,2 for advanced networking class 
    161. # Create-VM -name "DHCP1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.51/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
    162. # Create-VM -name "DHCP2" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.52/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
    163.  
    164. #    Create a second DC for reskit.org for advanced class 
    165. # Create-VM -name "DC2"  -vmPath $path -ReferenceVHD $ref -network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.11/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    166.  
    167.  
    168. #  script is all done - just say nice things and quit. 
    169. $Finish = Get-Date 
    170. "Create-VM --- Finished at: $Finish" 
    171. "Elapsed Time :  $(($Finish-$Start).totalseconds) seconds" 

    • Proposed as answer by CorpCaleCorp Monday, April 22, 2013 4:17 PM
    • Marked as answer by SANTOSH YAKKALA Tuesday, April 23, 2013 6:55 AM
    Monday, April 22, 2013 4:16 PM

All replies

  • Hi Guys,

    Can any help me on the above request

    Thanks and Regards

    Santosh

    Monday, April 22, 2013 12:53 PM
  • This by no means as easy task however I have found a website which can add you depend on you level of understanding in PS. this was created some time ago so the scripting would be simpler in PS3 however this is a good starting point. hope it helps

    Option Explicit
     
    Dim HyperVServer
    Dim VMName
    Dim WMIService
    Dim VSManagementService
    Dim VSGlobalSettingData
    Dim Result
    Dim Job
    Dim InParam
    Dim OutParam
     
    'Prompt for the Hyper-V Server to use
    HyperVServer = InputBox("Specify the Hyper-V Server to create the virtual machine on:")
     
    'Prompt for the new VM name
    VMName = InputBox("Specify the name for the new virtual machine:")
     
    'Get an instance of the WMI Service in the virtualization namespace.
    Set WMIService = GetObject("winmgmts:\\" & HyperVServer & "\root\virtualization")
     
    'Get the VirtualSystemManagementService object
    Set VSManagementService = WMIService.ExecQuery("SELECT * FROM Msvm_VirtualSystemManagementService").ItemIndex(0)
     
    ' Initialize a new global settings for the VM
    Set VSGlobalSettingData = WMIService.Get("Msvm_VirtualSystemGlobalSettingData").SpawnInstance_()
     
    'Set the VM name
    VSGlobalSettingData.ElementName = VMName
     
    'Setup the input parameter list
    Set InParam = VSManagementService.Methods_("DefineVirtualSystem").InParameters.SpawnInstance_()
    InParam.SystemSettingData = VSGlobalSettingData.GetText_(1) 
     
    'Execute the method and store the results in OutParam
    Set OutParam = VSManagementService.ExecMethod_("DefineVirtualSystem", InParam) 
     
    'Check to see if the job completed synchronously
    if (OutParam.ReturnValue = 0) then
       Wscript.Echo "Virtual machine created."
    elseif (OutParam.ReturnValue <> 4096) then
       Wscript.Echo "Failed to create virtual machine"
    else   
     
       'Get the job object
       set Job = WMIService.Get(OutParam.Job)
     
        'Wait for the job to complete (3 == starting, 4 == running)
       while (Job.JobState = 3) or (Job.JobState = 4)
          Wscript.Echo Job.PercentComplete
          WScript.Sleep(1000)
     
          'Refresh the job object
          set Job = WMIService.Get(OutParam.Job)
       Wend
     
       'Provide details if the job fails (7 == complete)
       if (Job.JobState <> 7) then
          Wscript.Echo "Failed to create virtual machine"
          Wscript.Echo "ErrorCode:" & Job.ErrorCode
          Wscript.Echo "ErrorDescription:" & Job.ErrorDescription
       else
          Wscript.Echo "Virtual machine created."
       end If
    end if

    PowerShell:

    # Prompt for the Hyper-V Server to use
    $HyperVServer = Read-Host "Specify the Hyper-V Server to create the virtual machine on"
     
    # Get name for new VM
    $VMName = Read-Host "Specify the name for the new virtual machine"
     
    # Create new MSVM_VirtualSystemGlobalSettingData object
    $wmiClassString = "\\" + $HyperVServer + "\root\virtualization:Msvm_VirtualSystemGlobalSettingData"
    $wmiClass = [WMIClass]$wmiClassString
    $newVSGlobalSettingData = $wmiClass.CreateInstance()
     
    # wait for the new object to be populated
    while ($newVSGlobalSettingData.psbase.Properties -eq $null) {}
     
    # Set the VM name
    $newVSGlobalSettingData.psbase.Properties.Item("ElementName").value = $VMName
     
    # Get the VirtualSystemManagementService object
    $VSManagementService = gwmi MSVM_VirtualSystemManagementService -namespace "root\virtualization" -computername $HyperVServer
     
    # Create the VM
    $result = $VSManagementService.DefineVirtualSystem($newVSGlobalSettingData.psbase.GetText(1))
     
    #Return success if the return value is "0"
    if ($Result.ReturnValue -eq 0)
       {write-host "Virtual machine created."} 
     
    #If the return value is not "0" or "4096" then the operation failed
    ElseIf ($Result.ReturnValue -ne 4096)
       {write-host "Failed to create virtual machine"}
     
      Else
       {#Get the job object
        $job=[WMI]$Result.job
     
        #Provide updates if the jobstate is "3" (starting) or "4" (running)
        while ($job.JobState -eq 3 -or $job.JobState -eq 4)
          {write-host $job.PercentComplete
           start-sleep 1
     
           #Refresh the job object
           $job=[WMI]$Result.job}
     
         #A jobstate of "7" means success
        if ($job.JobState -eq 7)
           {write-host "Virtual machine created."}
          Else
           {write-host "Failed to create virtual machine"
            write-host "ErrorCode:" $job.ErrorCode
            write-host "ErrorDescription" $job.ErrorDescription}

    http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/05/28/scripting-vm-creation-with-hyper-v.aspx

    Monday, April 22, 2013 4:09 PM
  • and I have found some more upto date info for you.

    This should do it

    http://pshscripts.blogspot.co.uk/2013/01/create-vmps1.html

    1. # Create-VM.ps1 
    2. # Script that creates VMs 
    3. # Version 1.0.0 - 20 Jan 2013 
    4. # See http://tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows-8.html 
    5.  
    6. # First define the Create-VM Function 
    7.  
    8. Function Create-VM { 
    9. #=================================================== 
    10. # Create a New VM 
    11. #=================================================== 
    12.  
    13. # Parameters are Name, Virtual Machine Path, path to reference Vhdx,
    14. # network switch to use, VM Memory, Unattend file, IP address and DNS
    15. # Server to set. Default values are specified in the Param block,
    16. # but these are normally overridden in the call to Create0VM 
    17.  
    18.  
    19. [Cmdletbinding()] 
    20. Param (  
    21.  $Name         = "Server"
    22.  $VmPath       = "C:\v3"
    23.  $ReferenceVHD = "C:\v3\Ref2012.vhdx"
    24.  $Network      = "Internal"
    25.  $VMMemory     = 512mb, 
    26.  $UnattendXML  = "C:\v3\unattend.xml"
    27.  $IPAddr       = '10.0.0.250/24'
    28.  $DnsSvr       = '10.0.0.10' 
    29.  
    30. $Starttime = Get-Date 
    31. Write-Verbose "Starting Create-VM at $Starttime" 
    32. Write-verbose "Creating VM: [$name]" 
    33. Write-verbose "Path to VM : [$VMpath]" 
    34.  
    35. #    Set path to differencing disk location 
    36. $path = "$vmpath\$name.vhdx" 
    37. Write-Verbose "Creating Disk at [$path]" 
    38.  
    39. #    Add a new differencing VHDX, Based on parent parent 
    40. $vmDisk01 = New-VHD –Path $path -Differencing –ParentPath $ReferenceVHD -ErrorAction Stop 
    41. Write-Verbose "Added VM Disk [$VMdisk01], pointing to [ReferenceVHD]" 
    42.  
    43. #    Create a New VM 
    44. $VM = New-VM –Name $name –MemoryStartupBytes $VMMemory –VHDPath $VMDisk01.path -SwitchName $Network -Path $vmPath 
    45. Write-Verbose "VM [$name] created" 
    46.  
    47. # Mount the Disk into the VM 
    48. Mount-DiskImage -ImagePath $path 
    49. $VHDDisk = Get-DiskImage -ImagePath $path | Get-Disk 
    50. $VHDPart = Get-Partition -DiskNumber $VHDDisk.Number 
    51. $VHDVolumeName = [string]$VHDPart.DriveLetter 
    52. $VHDVolume = [string]$VHDPart.DriveLetter + ":" 
    53. Write-verbose "Volume [$Volumename] created in VM [$name]" 
    54.  
    55.  
    56. #    Get Unattended.XML file 
    57. Write-Verbose "Using Unattended XML file [$unattendXML]" 
    58.  
    59. #    Open XML file 
    60. $Xml = [xml](get-content $UnattendXML
    61.  
    62. #    Change ComputerName 
    63. Write-Verbose "Setting VM ComputerName to: [$name]" 
    64. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-Shell-Setup" } | 
    65.  ForEach-Object
    66.    if($_.ComputerName) { 
    67.      $_.ComputerName = $name 
    68.    } 
    69.  
    70. #    Change IP address 
    71. Write-Verbose "Setting VM ComputerName to: [$name]" 
    72. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-TCPIP" } | 
    73.   ForEach-Object
    74.  
    75.     if($_.Interfaces) { 
    76.       $ht='#text' 
    77.       $_.interfaces.interface.unicastIPaddresses.ipaddress.$ht = $IPAddr 
    78.   } 
    79.  
    80. #    Change DNS Server address 
    81. #    Use obscure way to create the #TEXT node 
    82. Write-Verbose "Setting VM DNS address to: [$DNSSvr]" 
    83. $Xml.Unattend.Settings.Component | Where-Object { $_.Name -eq "Microsoft-Windows-DNS-Client" } | 
    84.   ForEach-Object
    85.       if($_.Interfaces) { 
    86.       $ht='#text' 
    87.       $_.Interfaces.Interface.DNSServerSearchOrder.Ipaddress.$ht = $DNSSvr 
    88.   } 
    89.  
    90. #    Save XML File on Mounted VHDX differencing disk 
    91. $xml.Save("$VHDVolume\Unattend.XML"
    92. Write-Verbose "Unattended XML file saved to vhd [$vhdvolume\unattend.xml]" 
    93.  
    94. #    Dismount VHDX  
    95. Write-Verbose "Dismounting disk image: [$Path]" 
    96. Dismount-DiskImage -ImagePath $path 
    97.  
    98. #    Update additional VM settings 
    99. Write-Verbose 'Setting additional VM settings' 
    100. Set-VM -Name $name -DynamicMemory 
    101. Set-VM -Name $name -MemoryMinimumBytes $VMMemory 
    102. Set-VM -Name $name -AutomaticStartAction Nothing 
    103. Set-Vm -Name $name -AutomaticStopAction ShutDown 
    104.  
    105. #    Show what has been created! 
    106. "VM Created:" 
    107. Get-VM -Name $name | fl * 
    108.  
    109. #    Start VM 
    110. Write-verbose "VM [$Name] being started" 
    111. Start-VM -Name $name 
    112.  
    113. #    Now work out and write how long it took to create the VM 
    114. $Finishtime = Get-Date 
    115. Write-Verbose ("Creating VB ($name) took {0} seconds" -f ($FinishTime - $Starttime).totalseconds) 
    116. # End of Create-VM function 
    117.  
    118.  
    119. ####################################################################################################### 
    120. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    121. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    122. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    123.  
    124. # Location of Server 2012 DVD Iso Image 
    125. $iso   = 'c:\Builds\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso' 
    126. # Where we put the reference VHDX 
    127. $ref   = 'c:\v3\Ref2012.vhdx' 
    128. # Path were VMs, VHDXs and unattend.txt files live 
    129. $path  = 'c:\V3' 
    130. # Location of Unattend.xml - first for workstation systems, second for domain joined systems  
    131. $una   = 'c:\V3\UnAttend.xml' 
    132. $unadj = 'c:\V3\UnAttend.dj.xml' 
    133.  
    134. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    135. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    136. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
    137. ####################################################################################################### 
    138.  
    139. #   Now run the script to create the VMs as appropriate. 
    140. $Start = Get-Date 
    141. "Create-VM --- Started at: $Start" 
    142.  
    143. #################################################################### 
    144. # Comment out VMs you do NOT want to create then run the entire script 
    145. # To comment out a VM creation, just add a '#" at the start of the line.  
    146. #        Removing the comment line means you want to create that VM.  
    147. #        BE creful!  If you make a mistake, stop the script. Kill any VMs created, then remove the 
    148. #        storage for the VMs.  
    149. ####################################################################################################### 
    150.  
    151. #    Create the DC - NON-domained joined 
    152. # Create-VM -name "DC1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $una -Verbose -IPAddr '10.0.0.10/24' -DNSSvr 10.0.0.10  -VMMemory 1gb 
    153.  
    154. #    Remaining VMs use the domain-join version of unattend.xml 
    155. # Create-VM -name "Srv1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.30/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    156. # Create-VM -name "Srv2"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.31/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    157. # Create-VM -name "Sql1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.20/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
    158. # Create-VM -name "Exch1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.21/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
    159.  
    160. #    DHCP 1,2 for advanced networking class 
    161. # Create-VM -name "DHCP1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.51/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
    162. # Create-VM -name "DHCP2" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.52/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
    163.  
    164. #    Create a second DC for reskit.org for advanced class 
    165. # Create-VM -name "DC2"  -vmPath $path -ReferenceVHD $ref -network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.11/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
    166.  
    167.  
    168. #  script is all done - just say nice things and quit. 
    169. $Finish = Get-Date 
    170. "Create-VM --- Finished at: $Finish" 
    171. "Elapsed Time :  $(($Finish-$Start).totalseconds) seconds" 

    • Proposed as answer by CorpCaleCorp Monday, April 22, 2013 4:17 PM
    • Marked as answer by SANTOSH YAKKALA Tuesday, April 23, 2013 6:55 AM
    Monday, April 22, 2013 4:16 PM
  • Hi CorpCaleCorp

    Thanks for the info, I'll try it today and post you in case of any help if required

    Thanks

    Santosh

    Tuesday, April 23, 2013 6:57 AM