Dung K Hoang 的个人资料Dung's space日志网络 工具 帮助

日志


7月23日

Delegation Model in Hyper-V – Part 6

 

In previous posts, I have shown how to create Azman scopes and roles to delegate administration of Hyper-V virtual machines to domain users. Now that we have an AzMan scope, let’s see how you can apply it to a virtual machine or set of virtual machines.

Note:  In Hyper-V, there is no GUI interface to assign a scope to a VM, you need to use the Hyper-V WMI API

In my example scenario, I have a set of VMs prefixed with “01_”and I want to delegate administration of those VMs to Student01 and only this account can view those VMs in Hyper-V mmc console. In Prt 4 and Part 5, I already created a scope called 01_Scope and some role definitions. Let’s apply this cope to 01_ VMs.

 

Script

$VM_Service = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemManagementService

$ListofVMs =get-wmiobject -namespace root\virtualization Msvm_ComputerSystem -filter  "ElementName <> Name "  | `
    where { $_.ElementName -like "01_*"}

foreach ($VM in $ListofVMs) {
        if ( $VM -ne $Null)
        {
        $VMGlobalSetting = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemGlobalSettingData | where `
           { $_.ElementName -like "*$($VM.ElementName)*" }

         $VMGlobalSetting.ScopeOfResidence = “01_Scope”

$VM_Service.ModifyVirtualSystem($VM.__PATH, $VMGlobalSetting.psbase.Gettext(1))

}

}

Et Voilà!

/Dung

HyperV WMI PowerShell

Delegation Model in Hyper-V – Part 5

 

Today, I will show you how to create an AzMan scope and role definition to manage Hyper-V Virtual machines.

As discussed in part 3, the ”Virtual Machine Manager Role” includes the following operations:

  1. "Allow Input to Virtual Machine",
  2. "Allow Output from Virtual Machine",
  3. "Start Virtual Machine",
  4. "Stop Virtual Machine",
  5. "Pause and Restart Virtual Machine”

For this role, you create a new scope in AzMan, define the role  and assign it to users inside this scope.

Step-by-Step

  1. Open a new MMC console. In the main window, click File –> Add/Remove snapin…. Add “Authorization Manager” to the console.
  2. Back to the console, right click the node Authorization Manager and select Open Authorization Store…” In the dialog box, ensure that option “Xml file” is selected, and click Browse. In the ‘browse” window, in the “file Name’ text box, type in C:\ProgramData\Microsoft\Windows\Hyper-V  and select Initialstore.xml. Your mmc should look like this one:


    pic-1
  3. Expand the hierarchy and right click Hyper-V Services and select New Scope. In the dialog box, fill out the name as  “01_scope” and click  OK.
  4. Under  01_Scope –> Definitions, right click Role Definitions and select New Role Definition. In the dialog box, fill out the name a “Virtual Machine Manager Role” and click  Add…
  5. In the Add Definition dialog box, click the “Operations” tab, then add the 2 operations specified above. Your screen should look like this one.
    ScreenShot064
  6. Under  01_Scope , right click Role Assignments and select New Role Assignment. In the Add Role dialog box, select “Virtual Machine  Manager Role”. Click OK.
  7. Back to the console, right click   “Virtual Machine Manager Role” and select Assign Users and Groups –> From Windows and Active Directory and specify Student01 as for my scenario.

In summary ,you have defined 2 roles in Azman and assign those roles to an user called Student01

  • Hyper-V Manager Role defined at the default scope ,i.e Hyper-V Services
  • Virtual Machine Manager role defined inside the 01_scope.

The Hyper-V Azman configuration should look like this one:

image

Note: Instead of assigning roles to user accounts, you can assign roles to a Windows Security group. For example, in my training environment, I create a SG called AllStudents and assign the Hyper-V Manager role to this SG.

 

Enjoy!

/Dung

HyperV WMI PowerShell

7月12日

Delegation Model in Hyper-V – Part 4

 

Now that you have a good understanding of AzMan, let’s implement a simple delegation model of Hyper-V. I use the following scenario as example. In my training labs, I have a group of students ( Student01, Student02….) to whom  I assign a set of VMs as follow: Student01 will get and can only manage 01_ VMs , Student02 will get 02_ VMs…

 

Basic AzMan roles

To delegate administration of a selected virtual machine to a user, an administrator needs to:

  1. Create specific AzMan roles and scope
  2. Apply scope to designated VMs

You need to define at least the following roles:

  • Hyper-V Manager Role”. This role includes the operations “Read Service Configuration” and “”View Virtual Switch Management”. The role is assigned to all users who want to connect to a Hyper-V host from the Hyper-V Manager Console. If a user is not assigned this role from AzMan, it will get an error message in the Hyper-V mmc stating that the credentials do not have sufficient permissions to connect to the service.
    Finally, as this role is used to define permissions to connect to the Virtual Machine Management Service, you create the role and assign users at the default scope of Hyper-V in AzMan.
    Note:  Name of the role is defined by the administrator. However, names of the operations are pre-defined and you must select the right operations when creating the role.
  • Virtual Machine Manager Role”.  This role includes the following operations:
    1. "Allow Input to Virtual Machine",
    2. "Allow Output from Virtual Machine",
    3. "Start Virtual Machine",
    4. "Stop Virtual Machine",
    5. "Pause and Restart Virtual Machine”

For this role, you create a new scope in AzMan, define the role  and assign it to users inside this scope and not at the default scope level.

 

Step-by-Step

In this section,I will show you how to create the roles in AzMan.

  1. Open a new MMC console. In the main window, click File –> Add/Remove snapin…. Add “Authorization Manager” to the console.
  2. Back to the console, right click the node Authorization Manager and select Open Authorization Store…” In the dialog box, ensure that option “Xml file” is selected, and click Browse. In the ‘browse” window, in the “file Name’ text box, type in C:\ProgramData\Microsoft\Windows\Hyper-V  and select Initialstore.xml. Your mmc should look like this one:


    pic-1
  3. Expand the hierarchy and right click Role Definitions and select New Role Definition. In the dialog box, fill out the name a “Hyper-V Manager Role” and click  Add…
  4. In the Add Definition dialog box, click the “Operations” tab, then add the 2 operations specified above. Your screen should look like this one.

    pic-2
  5. Now create a domain user named Student01. Use runas to open a MMC console with Student01’s credential. Add Hyper-V Manager snap-in to this console and try to connect to the local Hyper-V hot system. You should see the error like this one:

    pic-3
  6. Switch back to the Azman console. You will now assign this role to Student01. Right click Role Assignments and select New Role Assignment. In the Add Role dialog box, select “Hyper-V Manager Role”. Click OK.
  7. Back to the console, right click   “Hyper-V Manager Role” and select Assign Users and Groups –> From Windows and Active Directory and specify Student01 as for my scenario.
  8. Switch back to the Hyper-V console run under Student01’s profile, hit F5  to refresh, the error message should disappear!

You have successfully created the Hyper-V Manager Role. Bravo!

Enjoy!

/Dung

HyperV WMI PowerShell

7月8日

Delegation Model in Hyper-V – Part 3

 

Today, let’s discuss about basic Hyper-V operations defined in AzMan.

Displaying Hyper-V Operations

As explained in previous posts, all  pre-defined Hyper-V operations are stored in the InitialStore.XML file located under C:\Programdata\Microsoft\Windows\Hyper-V. You can view the list of operations from the AzMan console. However the output is not easy to view as is is confined inside a small dialog box.

Fortunately, you can also use PowerShell to get the same list with the AzMan COM object. Here is a snippet of PS script to get the list in a CSV file

$AppName = "Hyper-V Services"

##    Open the Hyper-V AzMan Store
##
$AZStore = new-object -COMObject AzRoles.AzAuthorizationStore
$AZStore.Initialize(0, "msxml://C:\ProgramData\Microsoft\Windows\Hyper-V\InitialStore.xml")

##
##    Access the  Default Scope
##
$HyperVApp     = $AZStore.OpenApplication($AppName)
$HyperVApp.Submit()

##
##   Get the list of operations
##

$HyperVApp | select Name, Description | export-csv c:\ListOfOperations.csv

You can then import the CSV file into Excel and create the following tables that group Hyper-V operations per category.

image

image

image

 

Enjoy!

/Dung

HyperV WMI PowerShell

7月7日

Delegation Model in Hyper-V – Part 2

 

In this post, I will show you how to explore the Hyper-V AzMan configuration  from the GUI

AzMan GUI interface

There is no pre-defined AzMan console in Windows Server 2008, you have to create your own one. To do this, run mmc.exe  from a command window. In the mmc, click File –> Add/Remove Snap-in  and add the snap-in named Authorization Manager.  Save your mmc console for later use.

In the AzMan mmc console, right click the node Authorization Manager and select  Open Authorization Store…. In the Open Authorization Store…, select XML file  and type in Store name:  C:\Programdata\Microsoft\Windows\Hyper-V\InitialStore.xml assuming that C: is your system drive.

Note: Be aware that the ProgramData folder is hidden, you cannot browse it.

Figure 1 shows the GUI interface of AzMan

AzMan-1

Exploring Hyper-V Operations

To see all pre-defined operations in Hyper-V, right click Tasks Definition and select New Task Definition…. Click Add…, ignore the informational message box. In the Add Definition  dialog box, click the Operations tab, you will see the list of available Hyper-V operations as shown in Figure 2 below

AzMan-2

Using the same technique, you can create task definitions, role definitions. Once done, you can look at the node Role Assignments to create roles and assign it to users or group of users.

Creating Scopes

Now, right click Hyper-V Services and select New Scope…  Provide a name for the new scope and you will see that a node is created under Hyper-V Services and has the following sub-hierarchy:

!------ Groups
!-------Definitions
!-------Role Assignments

All tasks, role definitions and role assignments created there will be valid only at this new scope level. On the other hand, tasks, role definitions created at the default scope level can be seen/used by the “child” scope.

Summary

It is quite easy to use the AzMan console to create tasks, roles and scopes. In the next posts, I will show how to use PowerShell scripts to automate those tasks!

Stay tuned!

 

Enjoy!

/Dung

HyperV WMI PowerShell

7月4日

Delegation Model in Hyper-V – Part 1

 

Overview

In MS Virtual Server 2005, to grant users access to virtual machines, you have to modify settings in two different places. First, you use the Web interface to change Security settings of Virtual Server and grant specific permissions to users ( Full Control, Read …). Second, you control access to the folders where virtual machines files are located with Access Control List (ACLs) set on files and folders.

Hyper-V uses a different authorization model which is based on Windows Authorization Manager (AzMan). AzMan is a role-based access control framework that provides runtime access validation methods for Windows applications. In contrast with the file-based access control model, AzMan offers the following advantages:

  • Granularity in permissions. File permissions are limited to basic actions such as read, write, full control on a resource. With AzMan, you can define more granular permissions and are not limited by the ACL model/
  • Permissions .vs Tasks. Using AzMan, application developers define permission/right as task to be assigned on resources. AzMan provides a broad authorization management model and much richer functionality
  • Storage.AzMan offers the ability to store defined policy in Active directory, ADAM, SQL database or even XML file.

AzMan exists since Windows 2003 R2 and is now an integrated component of the Windows platform. There are great resources that give an overview/ in-depth coverage of AzMan, you can find some good references here:

  • Role-Based Access Control for Multi-tier Applications Using Authorization Manager White P... : In the Windows Server 2003 family, Authorization Manager introduces a new model for application authorization on the Windows platform. AzMan gives applications a role-based access control framework that provides manageable administration and natural development for Web-based or line-of-business applications. http://technet2.microsoft.com/WindowsServer/en/library/72b55950-86cc-4c7f-8fbf-3063276cd0b61033.mspx
  • How to Use and Manage the Authorization Manager Snap-In : http://technet2.microsoft.com/WindowsServer2008/en/library/9bd3ff29-71de-466c-a0b9-30b225c1358e1033.mspx

     

    AzMan concepts

    There are basic concepts in AzMan that you need to be familiar with before we go into details on how Hyper-V implements/use it for delegation. I will not describe the architecture of AzMan here, you can find some excellent materials from the references listed above.

    • Operation: Low-level permission that a resource manager uses to identify security access. Examples of operations in Hyper-V: “Pause and Restart Virtual Machine”, “Start Virtual Machine”, “Create Virtual Switch”, “Read Service Configuration”….
    • Task: Group of operations. Task is used to define which operations are required for an admin person. For example, in Hyper-V AzMan , you can create a task called VM-Control which groups the following operations: “Pause and Restart Virtual Machine”, “Start Virtual Machine”…
    • Role Definition: Group of tasks and operations that are needed for a particular role. For example, you can create a role definition called “VM Operator” which includes the VM-Control task defined above and the “Read Service Configuration” operation
    • Role: Set of permissions a user must have to perform a particular job. Role is assigned to users or group and is applied to a set of objects through scope
    • Scope:  Defines a boundary for a distinct authorization policy. You create roles in a given scope and and apply this scope to a set of objects.

    So the scope is really the “link” between AzMan and Hyper-V, you apply a set of permissions ( created thru tasks and roles) of a scope to a set of Hyper-V objects. Hyper-V provides a Default Scope that applies to all Hyper-V objects, so if an object has no custom scope defined, then it will use the Default Scope. Hyper-V’s default scope is named “Hyper-V Services”.

    Scopes can be created from the default scope and they inherits tasks, roles definition and roles assignment from the parent scope. For example, if you create a new scope and apply to a set of objects, the objects will get all permissions ( through roles) defined in this scope and the default scope.

    Hyper-V objects and Scope

    All Hyper-V objects use the Default Scope but I find out that very few of them can accept user-defined scopes in the current release ( RC1) of Hyper-V. So far the following classes can have customized scopes:

    • Msvm_SwitchPort
    • Msvm_Switch
    • Msvm_VirtualSystemGlobalSettingData
    • Msvm_VirtualSystemManagementService

    Basically, only virtual machines, virtual switch and the Virtual Machine Management Service can accept custom AzMan scopes. Those objects have the property ScopeOfResidence defined in their base classes.

    To apply an Azman scope to those objects, you set their ScopeOfResidence to the name of the scope defined in AzMan. In the current release of Hyper-V , there is no GUI interface to apply a scope. You have to use scripts!

    Summary

    This is an overview of AzMan and how it is used in conjunction with Hyper-V. In the next posts, I will go through the AzMan interface and shows some scripts to create scopes and apply them to Hyper-V objects.

    Enjoy!

    /Dung

    HyperV WMI PowerShell

  • 7月2日

    MS TechNet webcast - Demo scripts

     

    For those who attended the MS TechNet webcast today, here are the scripts that I’ve used for the demo.

    I will have the AzMan demo scripts in a couple of days. Stay tuned!

     

    Demo 1: Create Virtual Switch

    ## ####################################################################
    ##
    ## DEMO - Create Virtual Networks
    ##
    ## ####################################################################
    ##
    ##     View current network settings in Hyper-V Manager
    ##
    read-host
    ##
    ##    Connect to the Virtual Switch Management Service
    ##
    $server = "localhost"
    $VS_Service = get-wmiobject -computername  $server  -namespace root\virtualization Msvm_VirtualSwitchManagementService
    $VS_Service | Get-member -member Method | where { $_.Name -like "*Switch" } | select Name
    cls
    ##
    ##    Create 2 private virtual networks
    ##
    ##
    ## 1st parameter: Name of the switch
    ## 2nd parameter: User-readable name of the switch.
    ## 3rd parameter: Maximum number of MAC addresses which will be learned by the switch
    #
    $VS_Service.CreateSwitch(“01_Corp”, “01_Corp”, 1024, “”)  | ft  CreatedVirtualSwitch, ReturnValue -auto
    $VS_Service.CreateSwitch(“01_Other”, “01_Other”, 1024, “”)  | ft  CreatedVirtualSwitch, ReturnValue -auto
    ##
    ##     Verify the results in the console
    ##
    cls
    ##
    ##    Create 10 private virtual networks
    ##
    2..5 | % { $i = "{0:D2}" -f $_ ; $n1 = "$($i)_Corp"; $n2 = "$($i)_Other" ; $VS_Service.CreateSwitch($n1, $n1, 1024, “”) | ft  CreatedVirtualSwitch, ReturnValue -auto ; $VS_Service.CreateSwitch($n2, $n2, 1024, “”) |  ft CreatedVirtualSwitch, ReturnValue -auto }
    ##     Verify the results in the console
    ##

    Demo2 : Import virtual machines

    ## ####################################################################
    ##
    ## DEMO - Import/Export VMs
    ##
    ## ####################################################################
    ##
    ##    Connect to the Virtual Machine Management Service
    ##
    $server = "localhost"
    $VM_Service = get-wmiobject -computername  $server  -namespace root\virtualization Msvm_VirtualSystemManagementService
    $VM_Service | Get-member -member Method | where {$_.Name -like "*VirtualSystem"} | select Name
    cls
    ##
    ##
    ##    Now we take a look at the Export folder structure:
    ##
    ##    <Drive:>\
    ##        | -----    XX_W2k3
    ##            | -------- Snapshots
    ##            | -------- Virtual Machines
    ##            | -------- Virtual Hard Disks
    ##       
    ##        | -----    XX_W2k8Full01
    ##    .......
    $ExportFolder = "Q:\"  
    ##
    ##    Scan the folders
    $ListOfFolders =  dir $ExportFolder  | where { $_.PSIsContainer}
    $ListOfFolders
    cls
    $ListOfFolders| % { $Folder= $_.Fullname.ToString(); $f = $_.Name.ToString(); write-host -fore Green "Importing $f ..." ; $VM_Service.ImportVirtualSystem($Folder,$True) | out-file tmp.txt }
    ##

    Demo 3: Change  VM’s states and take snapshots

    ## ####################################################################
    ##
    ##    DEMO - Changing state of VMs
    ##
    ## ####################################################################
    ##
    ##    Connect to the Virtual Management Service
    ##
    $State = @{‘Enabled’ = 2 ; ‘Disabled’= 3;  ‘Paused’= 32768 ; ‘Suspended’ = 32769 ; ‘Starting’ = 32770 ; ‘Snapshotting’ = 32771 ;  ‘Migrating’ = 32772 ; ‘Saving’ = 32773 ; ‘Stopping’ = 32774 ; ‘Deleted’ = 32775 ; ‘Pausing’ = 32776 }
    $state
    ##
    $Server = 'localhost'
    $VM_Service = get-wmiobject -computername $server -namespace root\virtualization Msvm_VirtualSystemManagementService
    ##
    ##  Step 1: Get list of VMs
    ##
    $Lists = get-wmiobject -computername $server  -namespace root\virtualization Msvm_ComputerSystem
    $Lists | get-member -member Method | ft Name
    $ListofVMs = $Lists | where {$_.ElementName -like "*01_*"}
    $ListofVMs | select ElementName, Name
    cls
    ##
    ##   Step 2: Save states
    ##
    foreach ($VM in $ListofVMs) {write-host -fore Green "Starting $($VM.ElementName)... " ;$VM.RequestStateChange($State['Enabled']) | out-file tmp.txt}
    ##
    ##     Check VM status from the Hyper-V Manager console
    ##
    cls
    ##
    ##   Step 3: Take snapshot
    ##
    $VM_Service | get-member -member Method | where { $_.Name -like "*snapshot*"} | select Name
    foreach ($VM in $ListofVMs) {write-host -fore Green "Taking snapshot of $($VM.ElementName) " ; $VM_Service.CreateVirtualSystemSnapShot($VM.__PATH) | out-file tmp.txt }
    ##

    Demo 4: Configure VMs’ resources

    ## ####################################################################
    ##
    ##    DEMO - Modifying resources of VMs
    ##
    ## ####################################################################
    ##
    ##    Check Boot order settings of 01_vista first
    ##      and stop 01_Vista
    ##
    ##    Connect to the Virtual Management Service
    ##
    $Server = 'localhost'
    $VM_Service = get-wmiobject -computername $server -namespace root\virtualization Msvm_VirtualSystemManagementService
    ##
    ##
    ##    Scenario 1 - Change Boot order in BIOS
    ##
    ##  Step 1: Get the VM objects
    ##
    $Lists = get-wmiobject -computername $server –namespace root\virtualization Msvm_ComputerSystem
    $ListofVMs = $Lists | where {$_.ElementName -ne $_.Name}
    $ListofVMs | select ElementName, Name
    cls
    $VM = $ListofVMs | where {$_.ElementName -like "*01*Vista*"}
    $VM_GUID = $VM.Name
    $VM | select ElementName, Name
    cls
    ##
    ##   Step 2: Get the "motherboard" settings of Vista01 VM
    ##
    $ListofMotherBoards = gwmi -computername $server -namespace root\virtualization Msvm_VirtualSystemSettingData
    $VM_MB = $ListofMotherBoards | where {$_.InstanceID -like "Microsoft:$VM_GUID"}
    $VM_MB | ft ElementName, InstanceID, BIOSSerialNumber, BootOrder
    ##
    ##    BootOrder:
    ##    0: Boot from floppy – 1: Boot from CD
    ##    2: Boot from disk – 3:PXE Boot
    ##
    cls
    ##
    ##   Step 3: Stop the VM
    ##
    $State = @{‘Enabled’ = 2 ; ‘Disabled’= 3;  ‘Paused’= 32768 ; ‘Suspended’ = 32769 ; ‘Starting’ = 32770 ; ‘Snapshotting’ = 32771 ;  ‘Migrating’ = 32772 ; ‘Saving’ = 32773 ; ‘Stopping’ = 32774 ; ‘Deleted’ = 32775 ; ‘Pausing’ = 32776 }
    $VM.RequestStateChange($State['Disabled'])
    ##
    ##   Step 4: Change the boot order
    ##
    ##    Possible values:
    ##    0: Boot from floppy – 1: Boot from CD
    ##    2: Boot from disk – 3:PXE Boot
    ##
    $VM_MB.BootOrder = 2,1,3,0
    $VM_Service.ModifyVirtualSystem($VM.__PATH, $VM_MB.psbase.GetText(1))
    ##
    ##     Verify the new setting in the console
    ##
    cls
    ## ####################################################################
    ##
    ##    DEMO - Modifying resources of VMs
    ##
    ## ####################################################################
    ##
    ##    Scenario 2  - Attach an ISO file to a DVD
    ##
    ##
    $ListOfRes = get-wmiobject -computername $server -namespace root\virtualization Msvm_ResourceAllocationSettingData
    $DvDrive = $ListofRes | where {($_.ResourceSubType -like "Microsoft Synthetic DVD Drive") -and ($_.InstanceID -like "*$VM_GUID*\1\0\*" )}  
    $DvDrive
    cls
    ##
    ##  Create a DVD disk.
    ##
    $DvDisk_Def = $ListofRes | where {($_.ResourceSubType -like "Microsoft Virtual CD/DVD Disk") -and ($_.InstanceID -like '*Default*' )}  
    $DvDisk_Def
    cls
    ##
    ##     Create a new instance from the default object
    ##
    $DvDisk = $DvDisk_Def.psbase.Clone()
    $DvDisk.Parent = $DvDrive.__PATH
    $DvDisk.Connection = "z:\Hyper-V_Demo\May_2008_Patch.iso"
    $DVDisk | fL Parent, Connection
    ##
    ##    Apply the changes
    ##
    $VM_Service.AddVirtualSystemResources($VM.__PATH, $DvDisk.psbase.Gettext(1))
    ##
    ##     Check settings of DVD  from the Hyper-V Manager console
    ##
    cls

    EnjoY!

    /Dung

    HyperV WMI PowerShell

    6月16日

    TechNet Webcast on Hyper-V WMI

     

    I will deliver a TechNet webcast next month to talk on Hyper-V WMI and PowerShell

    Here is the link for register

    http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032381324&EventCategory=4&culture=en-US&CountryCode=US

    Webcast Name: Managing Hyper-V Virtual Machines with WMI and Windows PowerShell (Level 300)

    Date: 7/2/2008 08:00 AM PST – 09:00 AM PST

     

    See you there!

    /Dung

    HyperV WMI PowerShell

    6月13日

    Hyper-V WMI Examples – Part XIX

     

    Virtual Machine creation – Revisiting the topic again

    Since I start the blog, I have seen many questions on how to create a new virtual machine and define resources such as memory, NICs at creation time. I must admit that the same question is in the back of my mind since a while and after looking at this blog entry of the Virtual PC guy, http://blogs.msdn.com/virtual_pc_guy/archive/2008/05/28/scripting-vm-creation-with-hyper-v.aspx, I decide to re-visit the topic and cover multiple scenarios here.

    In order to create a new virtual machine in Hyper-V, you must use the method DefineVirtualSystem  of the Msvm_VirtualSystemManagementService object. This method accepts 3 parameters:

    • SystemSettingData: an instance of Msvm_VirtualSystemGlobalSettingData
    • ResourceSettingData: an array of instances of Msvm_ResourceAllocationSettingData. Each instance represents a resource you want to add the virtual machine to be created.
    • SourceSetting: Refers to an existing Msvm_VirtualSystemSettingData that is used as template for creation of the VM

    It is quite intimidating for those who just want to create a virtual machine with resources pre-defined for this VM, but if you read this blog since the beginning, you will see that it’s quite simple :=).

    Scenario 1: Creating a blank VM

    I notice that if you call this method without any parameter, it will create a blank virtual machine! ( although the documentation mentions that the 1st parameter is mandatory). So in its simplest form, creating a VM can be achieved with 3 lines of scripts:

    Script

    $Server = “localhost”
    $VM_Service = get-wmiobject -computername $server -namespace root\virtualization Msvm_VirtualSystemManagementService

    $VM_Service.DefineVirtualSystem()

    The virtual machine will be created and displayed as “New Virtual Machine”

     

    Scenario 2: Creating a VM with a pre-defined name

    The blog post mentioned above shows how to create a new VM and specify a new display name at time of creation. I will not reproduce the code here but basically you create a new instance of the class MSvm_VirtualSystemGlobalSettingData, change the display name and then call DefineVirtualSystem.

     

    Scenario 3: Creating a VM and specifying resources

    In this scenario, I want to create a virtual machine with two NIC cards. For this, I will be leveraging some scripts developed/ shown in Hyper-V WMI Examples - Part XIV for creating network adapters. The first NIC will have static MAc Address while the second one will use dynamic MAC address.

    Script

    $Server = “localhost”
    $VM_Service = get-wmiobject -computername $server -namespace root\virtualization Msvm_VirtualSystemManagementService

    $VMGlobalSettingClass = [WMIClass]”\\Localhost\root\virtualization:Msvm_VirtualSystemGlobalSettingData"

    $NewGS = $VMGlobalSettingClass.psbase.CreateInstance()

    ## Now Create 2 NICs

    $GUID1 = [GUID]::NewGUID().ToString()
    $GUID2 = [GUID]::NewGUID().ToString()

    $DefaultNIC = gwmi -namespace root/virtualization Msvm_SyntheticEthernetPortSettingData | where {$_.InstanceID -like "*Default*"}

    $StaticNIC = DefaultNIC.psbase.Clone()
    $StaticNIC.VirtualSystemIdentifiers = “{$GUID1}”
    $StaticNIC.StaticMacAddress = $true
    $StaticNIC.Address = “00155D929001”

    $DynamicNIC = DefaultNIC.psbase.Clone()
    $DynamicNIC.VirtualSystemIdentifiers = “{$GUID2}”

    ## Build an array of resources as required by DefineVirtualSystem

    $RASD = @()

    $RASD += $StaticNIC.psbase.gettext(1)
    $RASD += $SDynamicNIC.psbase.gettext(1)

    ## Finally call DefineVirtualSystem

    $VM_Service.DefineVirtualSystem($NewGS.__PATH, $RASD)

    Et Voilà!

    Now that you understand the process, you can leverage my other examples to add DVD drive, new hard disks when creating virtual machines. I will leave it to you as homework for this weekend!

     

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    6月11日

    Hyper-V WMI Examples – Part XVIII

     

    How to find list of VMs connected to a given switch?

    In MS Virtual Server 2005, when looking at a virtual network, you can easily find a list of VMs that are attached to this network. Well, there is no easy way to find it within Hyper-V unless ….

    Andy Schneider has asked the  same question on getting a list of connected VMs per switch. So here is the result. Enjoy!

    Steps
    1. Get a list of switches
    2. Find all Switch ports created on a given switch
    3. Get all instances of Msvm_ActiveConnection.
    4. Match the  Antecedent attribute of Msvm_ActiveConnection with the PATH of SwitchPort
    5. When there is a match, find a VM whose GUID is listed in the Dependent attribute of Msvm_ActiveConnection
    Note

    The script finds all virtual machines that are attached to a given virtual machines. Those virtual machines must be running ,.ie. powered on to be listed by the script.

    Script

    $ListofVMs = gwmi -namespace root\virtualization Msvm_ComputerSystem -filter "ElementName <> Name"
    $ListofSwitches = gwmi -namespace root\virtualization Msvm_VirtualSwitch
    $ListofSwitchPorts = gwmi -namespace root\virtualization Msvm_SwitchPort

    foreach ($Switch in $ListofSwitches)
    {
        $SwitchGUID = $Switch.Name
        $SwitchDisplayName = $Switch.ElementName
        $PortsOnSwitch = $ListofSwitchPorts | where {$_.SystemName -match $SwitchGUID}

        foreach ($Port in $PortsOnSwitch)
        {
            $PortPath = $Port.__PATH
            $ListofConnections = gwmi -namespace root\virtualization Msvm_ActiveConnection
            $a = $ListofConnections | where {$_.Antecedent -like $PortPath}
            if ($a -ne $NULL)
            {
                $LANEndPoint = $a.Dependent
                foreach ($VM in $ListofVMs)
                {
                    $VMGUID = $VM.Name
                    $VMDisplayName = $VM.ElementName
                    if ($LanEndPoint -like "*$VMGUID*")
                    {
                        write-host "VM --> $VMDisplayName is connected to Switch --> $SwitchDisplayName"
                    }
                }
            }
        }
    }

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    6月10日

    Hyper-V WMI Explained - Part II

     

    Management Services

    In Hyper-V there are 3 services that govern all management activities of the virtual environment:

    • Hyper-V Virtual Machine Management Service (vmms) - This service is used to control creation, deletion and  modification of virtual machines. It also provides mechanisms to perform operations on virtual machines such as taking snapshots, importing and exporting virtual machines. in Hyper-V WMI, the service is represented by the class Msvm_VirtualSystemManagementService. If you want to take actions on virtual machines, you must first obtain an instance of this class by querying WMI and use one of its public methods.
      Example : $VM_Service = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemManagementService

     

    • Hyper-V Networking Management Service (nvspwmi) - This service is used to control creation, deletion of networking resources such as virtual switches, switch ports and internal Ethernet ports.  in Hyper-V WMI, the service is represented by the class Msvm_VirtualSwitchManagementService.
      Note:  the service does not manage network adapters (NICs) of virtual machines. NICs are resources of virtual machines so you need to use the Virtual Management Service.

     

    • Hyper-V Image Management Service (virtsvcs) - This service manages virtual media (.vhd, .vfd) for virtual machines..  in Hyper-V WMI, the service is represented by the class Msvm_ImageManagementService.

    The figure below maps various action items shown in the Hyper-V Manager console to the three services described above

    Hyper-V-Services

    Until the next time!

    Enjoy,

    /Dung

    HyperV WMI PowerShell

    Hyper-V WMI Explained - Part I

     

    Introduction

    I received many requests to explain some PowerShell examples on Hyper-V WMI so now it's great time to start a new series to dive in more detailed explanation about Hyper-V WMI.

    First let me say that your support through e-mail in the last few months are exceptional and I'd like to thank all the folks who send comments/suggestions to enhance the examples ( except for some scams in the blog!). Second let me write down a short disclaimer before going into technical details.

     

    Disclaimer

    All the information provided here are based on my own understanding of Hyper-V WMI during many hours of trials and tests. I use the two documents to learn about Hyper-V WMI:

    1. Hyper-V WMI documentation. The MSDN library contains Beta2 documentation of WMI.  Even though some classes/methods/properties are changed with the current release (Hyper-V RC1), most of them are still valid.
      Note:  I hope that MS will update the library ASAP when Hyper-V hits RTM
    2. DMTF CIM System Virtualization model: This is THE doc that you need to read/consult frequently if you are serious about using WMI and Hyper-V to build management tools. I know that MS is defining/pushing/using standards in the management space, so no surprise that they are using the virtualization model defined by the DMTF task force.

    In addition, I extensively use PowerShell and especially the get-member cmdlet to discover methods and properties of WMI object classes. This is a must if you want to write scripts or code against Hyper-V WMI. There certainly are other tools to browse WMI objects and I find Powershell quite handy for me.

    Finally, explanations provided are my interpretation of the documentation and based on my own testing. As such all the errors are also mine too!

    Now let's start then!

    /Dung

    HyperV WMI PowerShell

    6月6日

    Hyper-V WMI Examples - Part XVII

     

    Removing virtual machines from Hyper-V

    The following script is used to remove virtual machines from the Hyper-V console.

    ##    Connect to the Virtual Management Service
    ##
    $Server = 'localhost'
    $VM_Service = get-wmiobject -computername $server -namespace root\virtualization Msvm_VirtualSystemManagementService
    ##
    ## Remove "01_xxxx"Vms from the console
    ##
    $ListofVMs = get-wmiobject -computername $server -namespace root\virtualization Msvm_ComputerSystem | where {$_.ElementName -like '*01*'}
    foreach ($VM in $ListofVMs)
    {
        if ($VM -ne $Null)
        {
        $VM_Service.DestroyVirtualSystem($VM.__PATH)
        }
    }

     

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    6月3日

    Hyper-V WMI Examples - Part XVI

     

    Changing the Boot order of a VM

    Sometimes you may want to change the Boot order of a VM, for instance, to PXE boot a VM, to boot from a CD/DVD, or to simply fix the order to always start booting from the disk.

    You use the Msvm_VirtualSystemSettingData class to change the boot order setting f a VM. Objects of this class represents virtual "motherboard"" of a virtual machine and store virtualization-specific settings of a VM.

     

    Script

    $VMName = "My Virtual Machine"

    $VM_Service = get-wmiobject –namespace root\virtualization Msvm_VirtualSystemManagementService

    # Step 1

    $VM = get-wmiobject –namespace \root\virtualization Msvm_ComputerSystem | where {$_.ElementName -like $VMName )

    # Step 2 - Get its "motherboard"

    $MB = get-wmiobject –namespace \root\virtualization Msvm_VirtualSystemSettingData | where {$_.ElementName -like $VMName )

    # Step 3 - Change the Boot Order

    # Values are 0: Boot from floppy – 1: Boot from CD – 2: Boot from disk – 3:PXE Boot

    $MB.BootOrder = 3,1,2,0

    # Step 4

    $VM_Service.ModifyVirtualSystem($VM.__PATH, $MB.psbase.GetText(1))

     

    Et Voilà!

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    5月27日

    Hyper-V WMI Examples - Part XV

     

    Creating a new virtual machine from an existing virtual hard disk

    Due to numerous requests, I dedicate this entry to talk about creating a virtual machine from an existing virtual hard disk. It seems that some of you were not able to get it working using the example of adding a DVD as resource to an existing VM. I must admit that it's not intuitive and I still have to do it several times to make it right.
    Note:  The script is tested against Hyper-V RC1.

     

    Goal

    Create a new virtual machine based on an existing virtual hard disk. The VHD file is called C:\W2K3.VHD and the disk will be created on IDE Controller 0 at location 0.

    High level steps
    1. Create a new virtual machine
    2. Locate the IDE Controller 0
    3. Get the default Disk Drive instance. Create a new instance from the default one. Attach it to the IDE Controller 0 at location 0. Add the disk drive as new resource to the VM
    4. Get the default virtual hard disk instance. Create a new instance from the default one. Attach it to the disk drive. Connect it to the VHD file. Add the disk drive as new resource to the VM
    Script

    $VHDFile = "C:\W2K3.vhd"

    # Step 1

    $VM_Service = get-wmiobject –namespace root\virtualization Msvm_VirtualSystemManagementService
    $status = $VM_Service.DefineVirtualSystem()

    if ($status.ReturnValue -eq 0)
    {
        $NewVM_PATH = $status.DefinedSystem
    }

    # Step 2

    $ListOfControllers = get-wmiobject -namespace root\virtualization Msvm_ResourceAllocationSettingData `
                                        | where {$_.ResourceSubType -like "*Emulated*IDE*"}
    foreach ($Controller in $ListOfControllers)
    {
                if ($Controller.Address -eq 0)
                {
                # It must return exactly one controller. Let's assume that is the case
                $IDEController0 = $Controller
                }
    }

    # Step 3

    $DiskDefault = get-wmiobject -namespace root\virtualization Msvm_ResourceAllocationSettingData | `
                     where {($_.ResourceSubType -like "Microsoft Synthetic Disk Drive") –and   `
                     ($_.InstanceID -like '*Default*')}  

    $DiskDrive = $DiskDefault.psbase.Clone()
    $DiskDrive.Parent = $IDEController0.__PATH          # Attach to IDE Controller 0
    $DiskDrive.Address = 0                                                 # at Location 0
    $Status = $VM_Service.AddVirtualSystemResources($NewVM_PATH, $DiskDrive.psbase.GetText(1))
    if ($Status.ReturnValue –eq 0)
    {
                 $NewDiskDrive_PATH = $Status.NewResources
    }

    # Step 4

    $VHDDefault = get-wmiobject -namespace root\virtualization Msvm_ResourceAllocationSettingData | `
                     where {($_.ResourceSubType -like "Microsoft Virtual Hard Disk") –and `
                     ($_.InstanceID -like '*Default*' )}  

    $NewDiskDrive = [WMI]"$NewDiskDrive_PATH"
    $VHDisk = $VHDDefault.psbase.Clone()
    $VHDisk.Parent = $NewDiskDrive.__PATH            # Attach to the disk drive
    $VHDisk.Connection = $VHDFile
    $VM_Service.AddVirtualSystemResources($NewVM_PATH, $VHDisk.psbase.GetText(1))

     

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    5月17日

    Hyper-V WMI Examples - Part XIV

     

    Hyper-V Virtual Networks - Connecting virtual machines to a virtual network

    Now that you know how to create virtual networks, let me show how to connect a NIC of a given virtual machine to a network

    The script below is extracted from a discussion in the Virtualization Technet Forum. All credits go to AggieMatt!

    ## Assumes that  you already identify a virtual switch and store it in a variable called $Switch

    ## Create a new SwitchPort
    $VSwitch_Mgmt = gwmi -namespace root/virtualization Msvm_VirtualSwitchManagementService
    $VSwitch = gwmi -namespace root/virtualization Msvm_VirtualSwitch
    $PortName = "MyPortName"
    $Scope = ""
    $Status = $VSwitch_Mgmt.CreateSwitchPort($VSwitch, $PortName, $PortName, $Scope)
    $NewPortPath = $Status.CreatedSwitchPort
    ## Add a new SyntheticEthernetPort
    $DefaultNIC = gwmi -namespace root/virtualization Msvm_SyntheticEthernetPortSettingData | where {$_.InstanceID -like "*Default*"}
    $NewSyntheticNIC = $DefaultNIC.psbase.Clone()
    $NewSyntheticNIC.Connection = $NewPortPath
    $NewSyntheticNIC.ElementName = "Network Adapter"
    $SyntheticNICGUID = [guid]::NewGuid().ToString()
    $NewSyntheticNIC.VirtualSystemIdentifiers = "{" + $SyntheticNICGUID + "}"
    ## Apply the settings to the selected computer
    $VM_Mgmt = get-wmiobject -namespace root\virtualization Msvm_VirtualSystemManagementService
    $VMName = "MyVMName"
    $VM = get-wmiobject -namespace root\virtualization Msvm_ComputerSystem | where {$_.ElementName -like $VMName}
    $VM_Mgmt.AddVirtualSystemResources($VM.__PATH, $NewSyntheticNIC.psbase.gettext(1))

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    Hyper-V WMI Examples - Part XII

     

    Hyper-V Virtual Networks - Creating External Virtual Networks

    Finally let's see how you can create an External virtual network. Here is an overview of high level steps:

    External Virtual Network
    1. Find the Msvm_ExternalEthernetPort instance associated to a physical network adapter
    2. Call CreateSwitch to create a virtual network.
    3. Call CreateSwitchPort  to create at least 2 ports on the switch
    4. Call SetupSwitch  to create an external virtual network
    Script

    # Step 0: Connect to the Virtual Network Management Service
    $SW_Service = get-wmiobject –namespace root\virtualization Msvm_VirtualSwitchManagementService

    # Step 1
    $ThisPhysicalAdapter = get-wmiobject -namespace root\virtualization msvm_ExternalEthernetPort -filter "Name = 'Broadcom BCM5708C NetXtreme II GigE (NDIS VBD Client) #2' "

    ## Change the name used above to the name of your network adapter.

    # Step 2
    $Status = $SW_Service.CreateSwitch("External_Network", "External Virtual Network", 1024, "")

    # Store the path for later use
    $External_SwitchPATH = $Status.CreatedSwitchService

    # Step 3: Create two ports on the switch
    # Port for Internal
    $Status = $SW_Service.CreateSwitchPort($External_SwitchPATH, "Internal_Port" , "Internal Port for Host")

    # Store the path for later use
    $InternalSwitchPortPATH = $Status. CreatedSwitchPort

    # Port for External
    $Status = $SW_Service.CreateSwitchPort($External_SwitchPATH, "External_Port" , "External Port")

    # Store the path for later use
    $ExternalSwitchPortPATH = $Status. CreatedSwitchPort

    # Step 4
    $Status = $SW_Service.SetupSwitch($ExternalSwitchPortPATH, $InternalSwitchPortPATH, $ThisPhysicalAdapter, "Internal Network Adapter", "Internal NIC to External Virtual Network")

    Enjoy!

    /Dung

    HyperV WMI PowerShell

    5月15日

    Hyper-V WMI Examples - Part XI

     

    Hyper-V Virtual Networks - Creating Internal Virtual Networks

    Let's talk about how to create Internal Virtual Networks. In my previous post, I described the concept and high level steps to create internal virtual network.

    Steps to create a Internal Virtual Network
    1. Call CreateInternalEthernetPort to create a virtual NIC on the Hyper-V host system.
    2. Find the LAN Endpoint  associated to this virtual NIC by querying Msvm_LANEndPoint
    3. Call CreateSwitch to create a virtual network.
    4. Call CreateSwitchPort  to create at least one port on the switch
    5. Call ConnectSwitchPort to connect the port with the LAN Endpoint
    Script

    $SW_Service = get-wmiobject –namespace root\virtualization Msvm_VirtualSwitchManagementService

    ## Step 1

    $Status = $Sw_Service.CreateInternalEthernetPort("Internal Network Adapter", "Internal NIC", "020304050607" )

    if ($Status.ReturnValue -eq 0)

    {
    write-host "Internal Ethernet Port successfully created"
    $InternalEtherPortPATH = $Status.CreatedInternalEthernetPort
    }

    ## Step 2

    $NIC_Port = [WMI]$InternalEtherPortPATH
    # Get the name of this NIC
    $NIC_Name = $NIC_Port.Name

    # Find the LANEndPoint associated to this NIC
    $LANEndPoint = get-wmiobject -namespace root\virtualization Msvm_LanEndPoint -filter "Name = `'$($NIC_Name)`'"

    ## Step 3

    $Status = $SW_Service.CreateSwitch(“Internal_Network”, “Host and Guests Virtual Network”, 1024, “”)

    if ($Status.ReturnValue -eq 0)

    {
    write-host "Switch successfully created"
    $SwitchPATH = $Status.CreatedSwitchService
    }

    ## Step 4

    $Status = $SW_Service.CreateSwitchPort($SwitchPATH, "Internal_Port" , "Internal Port for Host")

    if ($Status.ReturnValue -eq 0)

    {
    write-host "SwitchPort successfully created"
    $PortPATH = $Status.CreatedSwitchPort
    }

    ## Step 5

    $Status = $SW_Service.ConnectSwitchPort($PortPATH , $LANEndPoint)

    ## Additional Step - Create a port to connect VM

    $Status = $SW_Service.CreateSwitchPort($SwitchPATH, "One_Port" , "A Switch Port to connect VM")

    if ($Status.ReturnValue -eq 0)

    {
    write-host "SwitchPort successfully created"
    $PortPATH = $Status.CreatedSwitchPort
    }

     

    Enjoy!

    /Dung

     HyperV WMI PowerShell

    5月13日

    Hyper-V WMI Examples - Part X

    Hyper-V Virtual Networks - Creating Private Virtual Networks

    In a previous post, I give you an overview of virtual networks and high-level steps to create virtual networks. Let's put it in practice today and show how to create a private virtual network.

    Steps to create a Private virtual network
    1. Call CreateSwitch to create a virtual network. By default, this method creates a private virtual network
    2. Call CreateSwitchPort  to create ports on the switch
    Script

    $SW_Service = get-wmiobject –namespace root\virtualization Msvm_VirtualSwitchManagementService

    # Call CreateSwitch
    # 1024 represents the max number of MAC addresses learnable by the switch
    # The 4th parameter represents the scope of residence and is not currently defined and used

    $Status = $SW_Service.CreateSwitch(“Private_Network”, “Guest only Virtual Network”, 1024, “”)

    if ($Status.ReturnValue -eq 0)

    {
    write-host "Switch successfully created"
    $SwitchPATH = $Status.CreatedSwitchService
    }

    ## Create a SwitchPort

    $Status = $SW_Service.CreateSwitchPort($SwitchPATH, "One_Port" , "A Switch Port to connect VM")

    if ($Status.ReturnValue -eq 0)

    {
    write-host "SwitchPort successfully created"
    $PortPATH = $Status.CreatedSwitchPort
    }

     

    Enjoy!

    /Dung

     HyperV WMI PowerShell

    5月12日

    Hyper-V WMI Examples - Part IX

     

    Hyper-V Virtual Networks

    Up to now, we've spent a significant amount of time and blog entries to talk about virtual machines. Let's switch gear and discuss about virtual networks.

    Networking Concepts

    In Hyper-V, you create virtual networks and connect virtual network cards (NICs) of virtual machines to allow communications between the machines themselves, the host system and eventually the physical network.

    A virtual network, also called Virtual Switch can be one of the three following types:

    · Private: Virtual machines connected to this network can communicate between them. The host system has no connectivity with virtual machines

    · Internal: Virtual machines connected to this network can communicate between themselves and the host system. There is no connectivity with the physical network.

    · External: An external virtual network binds to the physical network adapter so that virtual machines as well as the host system can access the physical network.

    Virtual networks and connections of virtual machines to virtual networks are managed by a Hyper-V service called Virtual Switch Management Service. There is a WMI class associated to this service called Msvm_VirtualSwitchManagementService.

     
    Private Virtual Network

    When you create a private virtual network, the Virtual Network Manager Service running on the host system will create a Virtual Switch and allows you to connect virtual machines to this switch. The host system does not participate in this private network, as such, cannot communicate with virtual machines connected to it. This type of network is also known as "Guest-Only Network" or "Private Virtual Machine Network". The figure below shows a visual representation of a private virtual network.

     image

     

     

     

     

     

     

     

     

     

     

    Internal Virtual Network

    When you create an Internal virtual network, the Virtual Network Manager Service running on the host system will create:

    · A virtual network

    · A virtual NIC on the host system that will be connected to the virtual network.

    As such, all virtual machines connected to the Internal virtual network can communicate with the host system and vice-versa. It is important to note that existing physical network adapters are left untouched. The figure below shows a visual representation of an internal virtual network.

     image

     

     

    External Virtual Network

    When you create an External virtual network, you specify a physical network adapter for the virtual network to bind to. As a consequence, the Virtual Network Manager Service running on the host system will create:

    · A virtual network

    · A virtual NIC on the host system that will be connected to the virtual network

    The physical network adapter will then be connected to the virtual network. The latter will be acting as a router and allow both virtual machines and host system to connect to the physical network. Figure 3 illustrates the concept of an external virtual network.

    It's interesting to note that:

    • all the existing network connections to the host system will be lost as soon as you create an external virtual network that binds to a unique physical NIC of the host system. The host is now “connected” to the physical network through the virtual NIC and the virtual “switch”
    • You cannot create an external virtual networks that is bound to a wireless adapter.

    The figure below illustrates the concept of an external virtual network.

    image

     

     

    How to connect a virtual machine to a virtual network?

    Now that you understand the concept of virtual network, your next question would be to connect a virtual machine to a virtual network.

    Assume that your virtual machine already has a NIC and that you have created a virtual network, you will need to create a port on the virtual network, or to be exact, create a SwitchPort, and then associate this SwtichPort to a NIC by setting  the Connection property of the NIC to the WMI Path of the SwitchPort.

    If your virtual machine does not have a NIC, you need to create one by duplicating the default instance of Msvm_SyntheticEthernetPortSettingData and perform the same operations as above.

    Overview of Msvm_VirtualSwitchManagementService

    The Msvm_VirtualSwitchManagementService class is used to control the creation and configuration of virtual networks. As you can see from the explanations above, there are two distinct tasks in virtual networks management. First you create a virtual network and define its type – private, internal, external. Once the virtual network created, you then create ports on the switch for network connections. Second you connect virtual NICs (either from virtual machines or the host system) to a virtual network. The Msvm_VirtualSwitchManagementService class provides several methods to create virtual networks and configure its type. Creating a virtual network is very easy and consists of a single-step operation. To configure the type, you may need additional steps.

    Here is a high-level overview of steps to create and configure virtual networks. All the methods listed below come from the Msvm_VirtualSwitchManagementService class.

    Private Virtual Network
    1. Call CreateSwitch to create a virtual network. By default, this method creates a private virtual network
    2. Call CreateSwitchPort  to create ports on the switch
    Internal Virtual Network
    1. Call CreateInternalEthernetPort to create a virtual NIC on the Hyper-V host system.
    2. Find the LAN Endpoint  associated to this virtual NIC by querying Msvm_LANEndPoint
    3. Call CreateSwitch to create a virtual network.
    4. Call CreateSwitchPort  to create at least one port on the switch
    5. Call ConnectSwitchPort to connect the port with the LAN Endpoint

     

    External Virtual Network
    1. Find the Msvm_ExternalEthernetPort instance associated to a physical network adapter
    2. Call CreateSwitch to create a virtual network.
    3. Call CreateSwitchPort  to create at least 2 ports on the switch
    4. Call SetupSwitch  to create an external virtual network

    That's it!

    Until next time...

    /Dung

     HyperV WMI PowerShell