PowerShell: Add Network Sites (VLAN) into a Virtual Machine Manager Logical Network

# addVmmNetworkSites.ps1
# version 0.01

# User Defined Variables
$networkSites=@(
    @{
        'newNetworkSitename'="test 1"
        'vlanId'=100
        'vlanCidr'='192.168.1.0/24'
        'logicalNetworkName'='Trunk'
        'logicalNetworkDescription'=''
        'hostGroup'='All Hosts'
    }
    @{
        'newNetworkSitename'="test 2"
        'vlanId'=200
        'vlanCidr'='192.168.2.0/24'
        'logicalNetworkName'='Trunk'
        'logicalNetworkDescription'=''
        'hostGroup'='All Hosts'
    }    
)

function addVmmNetworkSite{
    param(
        $newNetworkSitename,
        $vlanId,
        $vlanCidr,
        $logicalNetworkName='Trunk',
        $logicalNetworkDescription='',
        $hostGroup='All Hosts',        
        $runAsynchronously=$true
    )

    # Set the logical network with required features of network virtualization
    $logicalNetwork = Get-SCLogicalNetwork -Name $logicalNetworkName
    $setLogicalNetwork="Set-SCLogicalNetwork -Name '$logicalNetworkName' ``
        -Description '$logicalNetworkDescription' ``
        -LogicalNetwork `$logicalNetwork ``
        -EnableNetworkVirtualization `$true ``
        -UseGRE `$true ``
        -LogicalNetworkDefinitionIsolation `$false ``
        $(if($runAsynchronously){'-RunAsynchronously'})"
    write-host $setLogicalNetwork
    invoke-expression $setLogicalNetwork

    # Add network site
    $allHostGroups = @()
    $allHostGroups += Get-SCVMHostGroup -Name $hostGroup
    $allSubnetVlan = @()
    $allSubnetVlan += New-SCSubnetVLan -Subnet $vlanCidr -VLanID $vlanId
    $addNetworkSite="New-SCLogicalNetworkDefinition -Name '$newNetworkSitename' ``
        -LogicalNetwork `$logicalNetwork ``
        -VMHostGroup `$allHostGroups ``
        -SubnetVLan `$allSubnetVlan ``
        $(if($runAsynchronously){'-RunAsynchronously'})"
    write-host $addNetworkSite
    invoke-expression $addNetworkSite
}

foreach($networkSite in $networkSites){
    $command="addVmmNetworkSite -newNetworkSitename '$($networkSite.newNetworkSitename)' ``
        -vlanId '$($networkSite.vlanId)' ``
        -vlanCidr '$($networkSite.vlanCidr)' ``
        -logicalNetworkName '$($networkSite.logicalNetworkName)' ``
        -logicalNetworkDescription '$($networkSite.logicalNetworkDescription)' ``
        -hostGroup '$($networkSite.hostGroup)'"
    write-host $command
    #invoke-expression $command
}

Leave a Reply

Your email address will not be published. Required fields are marked *