Skip to content

Instantly share code, notes, and snippets.

@mlocati
Last active July 30, 2020 16:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlocati/bb146577785511b44412e2fb57f969a6 to your computer and use it in GitHub Desktop.
Save mlocati/bb146577785511b44412e2fb57f969a6 to your computer and use it in GitHub Desktop.
Enable or disable Hyper-V (to switch between VirtualBox and Docker for Windows, for example)
<#
To enable Hyper-V:
Enable-HyperV.ps1 $True
To disable Hyper-V:
Enable-HyperV.ps1 $False
Author: Michele Locati <michele@locati.it>
License: MIT
Source: https://gist.github.com/mlocati/bb146577785511b44412e2fb57f969a6
#>
param(
[Parameter(Mandatory = $true, HelpMessage = 'Enable or disable?')]
[ValidateNotNullOrEmpty()]
$Enable
)
$features = @(
'Microsoft-Hyper-V-All',
'HypervisorPlatform',
'VirtualMachinePlatform',
'Containers'
)
if ($Enable -eq $true -or $Enable -eq 1 -or $Enable -eq '1' -or $Enable -eq 'y' -or $Enable -eq 'yes' -or $Enable -eq 'on') {
$parsedEnable = $true
} elseif ($Enable -eq $false -or $Enable -eq 0 -or $Enable -eq '0' -or $Enable -eq 'n' -or $Enable -eq 'no' -or $Enable -eq 'off') {
$parsedEnable = $false
} else {
Write-Error 'Invalid argument'
return
}
$currentUser = [System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()
if ($currentUser.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
if ($parsedEnable) {
Write-Host "Setting HypervisorLaunchType to auto"
bcdedit.exe /set hypervisorlaunchtype auto
} else {
Write-Host "Setting HypervisorLaunchType to off"
bcdedit.exe /set hypervisorlaunchtype off
}
$restartNeeded = $false
ForEach ($feature in $features) {
if ($parsedEnable) {
Write-Host "Enabling feature $feature..."
$result = Enable-WindowsOptionalFeature -Online -FeatureName $features -Verbose -NoRestart
} else {
Write-Host "Disabling feature $feature..."
$result = Disable-WindowsOptionalFeature -Online -FeatureName $features -Verbose -NoRestart
}
if ($result -and $result.RestartNeeded) {
$restartNeeded = $true
}
}
if ($restartNeeded) {
Write-Host "`n`nYOU SHOULD RESTART THE COMPUTER TO ACTIVATE THE CONFIGURATION.`n`n"
Restart-Computer -Confirm
}
return
}
$exeCommand = "$PSCommandPath -Enable $parsedEnable"
Start-Process -FilePath 'powershell.exe' -ArgumentList "-Command ""$exeCommand""" -Verb RunAs -WindowStyle Normal -Wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment