-- Ben Armstrong, Virtualization Program Manager
Talking about core virtualization at Microsoft (Hyper-V, Virtual PC and Virtual Server).
I spent a bunch of time scripting virtual networks under Hyper-V over the weekend – so this week I am going to share some of my scripts. The first one is a simple one: it creates a private – or “virtual machine only” – virtual network.
VBScript:
option explicit
Dim HyperVServer
Dim FriendlyName
Dim TypeLib
Dim SwitchName
Dim WMIService
Dim VirtualSwitchManagementService
Dim InParam
Dim OutParams
'Prompt for the Hyper-V Server to use
HyperVServer = InputBox("Specify the Hyper-V Server to create the VM only virtual network switch:")
'Get friendly name for the VM only virtual network switch
FriendlyName = InputBox("Specify the name of the new VM only virtual network switch:")
'Generate GUID for the unique switch name
Set TypeLib = CreateObject("Scriptlet.TypeLib")
SwitchName = TypeLib.Guid
'Get an instance of the WMI Service in the virtualization namespace.
set WMIService = GetObject("winmgmts:\\" & HyperVServer & "\root\virtualization")
'Get the Msvm_VirtualSwitchManagementService object
set VirtualSwitchManagementService = WMIService.ExecQuery("select * from Msvm_VirtualSwitchManagementService").ItemIndex(0)
'Setup the input parameter list
set InParam = VirtualSwitchManagementService.Methods_("CreateSwitch").InParameters.SpawnInstance_()
InParam.FriendlyName = FriendlyName
InParam.Name = SwitchName
InParam.NumLearnableAddresses = 1024
InParam.ScopeofResidence = null
'Execute the method and store the results in OutParam
set OutParams = VirtualSwitchManagementService.ExecMethod_("CreateSwitch", InParam)
'Report the results
if OutParams.ReturnValue = 0 then
Wscript.Echo "Created a new VM only virtual network."
else
Wscript.Echo "Failed to create a new VM only virtual network."
end if
PowerShell:
# Prompt for the Hyper-V Server to use
$HyperVServer = Read-Host "Specify the Hyper-V Server to use (enter '.' for the local computer)"
# Get friendly name for the VM only virtual network switch
$SwitchFriendlyName = Read-Host "Specify the name of the new VM only virtual network switch"
# Generate GUID for the unique switch name
$SwitchName = [guid]::NewGuid().ToString()
# 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, "1024","")
As you can see, all you need to do is to call the CreateSwitch method on the MSVM_VirtualSwitchManagementService. CreateSwitch takes four parameters:
Cheers, Ben