问题
I am trying to write a PowerShell script that checks the Windows Optional Features to see if Hyper-V is installed. However, my code is not working. Even when Hyper-V is disabled, the script outputs that it is already enabled.
#Requires -RunAsAdministrator
# Get the Hyper-V feature and store it in $hyperv
$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online
# Check if Hyper-V is already enabled.
if($hyperv.State = "Enabled") {
Write-Host "Hyper-V is already enabled."
} else {
Write-Host "Hyper-V is disabled."
}
There is no error when the code is run.
回答1:
I believe it has to do with your if
condition, try this:
if($hyperv.State -eq "Enabled")
The =
sign is not going to work, you need to do it PowerShell way
回答2:
Here's the full powershell script that works for me. Just copy and paste it into an elevated powershell then press enter.
$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online
# Check if Hyper-V is enabled
if($hyperv.State -eq "Enabled") {
Write-Host "Hyper-V is enabled."
} else {
Write-Host "Hyper-V is disabled."
}
回答3:
An easier way to do that is to go to Services by clicking the Start button and typing Services.msc and scrolling down to the Hyper-V Host Compute Service and seeing if it running. Also check the Hyper-V Virtual Machine Management service.
If they are both running you can safely assume that Hyper-V is running and active. My machine Windows 10 Pro with VMWARE Workstation 14.
来源:https://stackoverflow.com/questions/37567596/how-do-you-check-to-see-if-hyper-v-is-enabled-using-powershell