none
Creating a new VM and attach a VHD and a Virtual Network Adapter RRS feed

  • Question

  • Hi,

    I have to write a powershell script to create several VM on a Hyper-V System. I use the VHDTool.exe and a script to create a blank VM, by Virtual PC Guy.
    My Problem is I am not able to attach the createt VHD and Virtual Network Adapter to the blank VM.

    The Path of the VHD is: D:\test.vhd


    The code to create a VM:

    $strHPassword = "VM123654"<BR>  
    <P>$SecurePassword = ConvertTo-SecureString "$strHPassword" -AsPlainText   
    -Force</P> 
    <P>New-VM -Template $Template -Name "VM$strHNO" -Description "$strUserName"   
    -VMHost $VMHost -Path "$strDiskPart\Hyper-V" -JobGroup $JobGroupId   
    -RunAsynchronously -Owner "RHVMM\$strKNO" -HardwareProfile $HardwareProfile   
    -ComputerName "VM$strHNO" -ProductKey "KEY HERE" -TimeZone 130   
    -AdminPasswordCredential $SecurePassword -GuiRunOnceCommands "netsh interface   
    ipv4 set address ""Local Area Connection"" source=static $strIpAddress   
    255.255.255.248 $strGateway", "netsh interface ipv4 add dnsserver ""Local Area   
    Connection"" 77.75.34.10", "netsh interface ipv4 add dnsserver ""Local Area   
    Connection"" 77.75.34.20 index=2" -JoinWorkgroup "WORKGROUP"&nbsp; -AnswerFile   
    $null -OperatingSystem $OperatingSystem -RunAsSystem -StartAction   
    TurnOnVMIfRunningWhenVSStopped -DelayStart 0 -StopAction SaveVM -StartVM</P>

    The code to create the Virtual Network Adapter:
    # Prompt for the Hyper-V Server to use
    $HyperVServer = "localhost"
    
    # List the available physical network adapters
    Write-Host "The following physical network adapters are avaiable for an external virtual network:"
     
    # Get the collection of external network adapters that are not associated with switches
    $query = "Select * From Msvm_ExternalEthernetPort WHERE IsBound=False AND EnabledState=2"
    $ExternalEthernetPorts = gwmi -namespace "root\virtualization" -Query $query -computername $HyperVServer
     
    # Output the elementname for each external nic
    foreach ($Nic in $ExternalEthernetPorts)       
       {          
          Write-Host $Nic.Name       
       } 
     
    # Keep on asking for a physical network adapter until we get a valid answer
    $ExternalEthernetPort = $null
     
    While ($ExternalEthernetPort -eq $null)
       {
       # Ask for the NIC name to use for the switch
       $ExternalEthernetPortName = Read-Host "Please type in the (exact) name of the network adapter you want to use for the external connection"
    
       # Get the WMI object for the external nic
       $query = "Select * From Msvm_ExternalEthernetPort WHERE Name='" + $ExternalEthernetPortName + "' AND IsBound=False AND EnabledState=2"
       $ExternalEthernetPort = gwmi -namespace "root\virtualization" -Query $query -computername $HyperVServer
       }
    # Get friendly name for the external virtual network switch (and internal ethernet port)
    $SwitchFriendlyName = "Script_created_LAN"
    
    $InternalEthernetPortFriendlyName = $SwitchFriendlyName
     
    # Set the friendly name for the internal switch port and external switch port
    $InternalSwitchPortFriendlyName = "InternalSwitchPort"
    $ExternalSwitchPortFriendlyName = "ExternalSwitchPort"
     
    # Generate GUIDs for the unique switch name, internal switch port name, internal ethernet port name and external switch port name
    $SwitchName = [guid]::NewGuid().ToString()
    $InternalSwitchPortName = [guid]::NewGuid().ToString()
    $InternalEthernetPortName = [guid]::NewGuid().ToString()
    $ExternalSwitchPortName = [guid]::NewGuid().ToString()
     
    # Setup some other values that will be used
    $NumLearnableAddresses = 1024
    $ScopeOfResidence = ""
     
    # Get the Msvm_VirtualSwitchManagementService WMI Object on the system we are going to be working with
    $VirtualSwitchManagementService = gwmi Msvm_VirtualSwitchManagementService -namespace "root\virtualization" -computername $HyperVServer
     
    # Create a new switch with 1024 learnable addresses
    $Result = $VirtualSwitchManagementService.CreateSwitch($SwitchName, $SwitchFriendlyName, $NumLearnableAddresses, $ScopeOfResidence) 
     
    # Get the WMI object for the new switch out of the results
    $Switch = [WMI]$Result.CreatedVirtualSwitch 
     
    # Create Internal Switch Port 
    $Result = $VirtualSwitchManagementService.CreateSwitchPort($Switch, $InternalSwitchPortName, $InternalSwitchPortFriendlyName, $ScopeOfResidence)
     
    # Get the WMI object for the new switch port out of the results
    $InternalSwitchPort = [WMI]$Result.CreatedSwitchPort 
     
    # Create External Switch Port 
    $Result = $VirtualSwitchManagementService.CreateSwitchPort($Switch, $ExternalSwitchPortName, $ExternalSwitchPortFriendlyName, $ScopeOfResidence)
     
    # Get the WMI object for the new switch port out of the results
    $ExternalSwitchPort = [WMI]$Result.CreatedSwitchPort 
     
    # Pull it all together with a call to SeutpSwitch
    $Result = $VirtualSwitchManagementService.SetupSwitch($ExternalSwitchPort, $InternalSwitchPort, $ExternalEthernetPort, $InternalEthernetPortName, $InternalEthernetPortFriendlyName)
     
    # Return success if the return value is "0"
    if ($Result.ReturnValue -eq 0)
       {write-host "External virtual network created."} 
     
    # If the return value is not "0" or "4096" then the operation failed
    ElseIf ($Result.ReturnValue -ne 4096)
       {write-host "Failed to create external virtual network."}
     
      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 "External virtual network created."}
          Else
           {write-host "Failed to create external virtual network."
            write-host "ErrorCode:" $job.ErrorCode
            write-host "ErrorDescription" $job.ErrorDescription}
       }
    
    Thanks for help,

    DawidK
    • Edited by DawidK Tuesday, May 12, 2009 1:39 PM übersichtlichkeit
    Tuesday, May 12, 2009 1:38 PM

Answers

  • Why aren't you using the VMM cmdlet New-VirtualNetworkAdapter?

    Here is a simplified example:

    # Create a hardware profile for use in the New-VM command
    #
    $hwprofile = New-HardwareProfile -Name "Medium VM" -MemoryMB 512


    # Now add a network adapter to the hardware profile.  Use the command Get-Help New-VirtualNetworkAdapter -detailed to see all of the options for the cmdlet
    #
    New-VirtualNetworkAdapter -HardwareProfile $hwprofile

    Tuesday, May 12, 2009 3:44 PM

All replies

  • Why aren't you using the VMM cmdlet New-VirtualNetworkAdapter?

    Here is a simplified example:

    # Create a hardware profile for use in the New-VM command
    #
    $hwprofile = New-HardwareProfile -Name "Medium VM" -MemoryMB 512


    # Now add a network adapter to the hardware profile.  Use the command Get-Help New-VirtualNetworkAdapter -detailed to see all of the options for the cmdlet
    #
    New-VirtualNetworkAdapter -HardwareProfile $hwprofile

    Tuesday, May 12, 2009 3:44 PM
  • VMM is too expensive for our client.

    There for I have to script it.
    Wednesday, May 13, 2009 8:00 AM