Private/New-LabVirtualSwitch.ps1
function New-LabVirtualSwitch { [CmdletBinding()] Param( [Parameter (Mandatory=$true)] [string]$SwitchName, [switch]$Force ) try { $Message = "The virtual switch '$SwitchName' already exists" if (Get-VMSwitch -Name $SwitchName -ErrorAction SilentlyContinue) { if ($Force -eq $false) { throw "$Message." } elseif ($VM = Get-VM | Get-VMNetworkAdapter | Where-Object Status -eq 'Ok' | Where-Object SwitchName -eq $SwitchName -ErrorAction SilentlyContinue) { $VMs = $VM.name -join ',' throw "$Message but cannot be deleted because it is being used by running VM(s) $VMs." } else { Write-Verbose "$Message. Replacing with a new one..." Remove-VMSwitch $SwitchName -Force } } New-VMSwitch -Name $SwitchName -SwitchType Internal | Out-Null } catch { $PSCmdlet.ThrowTerminatingError($_) } } |