Last active
July 30, 2020 16:23
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
To enable Hyper-V: | |
Enable-HyperV.ps1 $True | |
To disable Hyper-V: | |
Enable-HyperV.ps1 $False | |
Author: Michele Locati <[email protected]> | |
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