Skip to content

Set-HyperVVMNetworkSwitch

Hyper-V: Connects or disconnects virtual machine network adapters to a switch

#Requires -Version 5.1
#Requires -Modules Hyper-V

[CmdletBinding()]
Param (
    [string]$ComputerName = "localhost",

    [PSCredential]$Credential,

    [Parameter(Mandatory = $true)]
    [string]$Name,

    [string]$SwitchName,

    [switch]$Disconnect
)

Process {
    try {
        $params = @{
            'ComputerName' = $ComputerName
            'ErrorAction'  = 'Stop'
        }
        if ($Credential) { $params.Add('Credential', $Credential) }

        $vm = Get-VM @params | Where-Object { $_.Name -eq $Name -or $_.Id -eq $Name }

        if (-not $vm) {
            throw "Virtual machine '$Name' not found on '$ComputerName'."
        }

        $adapters = Get-VMNetworkAdapter -VM $vm -ErrorAction Stop

        if ($Disconnect) {
            $adapters | Disconnect-VMNetworkAdapter -ErrorAction Stop
        }
        elseif ($SwitchName) {
            $adapters | Connect-VMNetworkAdapter -SwitchName $SwitchName -ErrorAction Stop
        }

        $results = Get-VMNetworkAdapter -VM $vm | Select-Object Name, SwitchName, MacAddress, Status

        $result = [PSCustomObject]@{
            VMName    = $vm.Name
            Adapters  = $results
            Action    = if ($Disconnect) { "NetworkDisconnected" } else { "NetworkSwitchUpdated" }
            Status    = "Success"
            Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
}

Specifies the name of the Hyper-V host. Defaults to the local machine.

Specifies the credentials to use for the remote connection.

Specifies the name or ID of the virtual machine.

Optional. Specifies the name of the virtual switch to connect to. If not provided, adapters will be disconnected.

Off

Optional. If set, disconnects all network adapters from any virtual switch.

An interactive directory of PowerShell scripts.