Powershell Script- Installing windows features

Recently, ive came across one task to create PowerShell script which does the following actions

  1. check and install if Hyper-V role is missing
  2. Check and install if WSL is missing
  3. Check and add the local user account to Hyper-v Admin group so they can use Hyper-v without admin privileges.

Following is the script, it’s dirty script since the last function is not doing its job properly if anyone finds a solution please reach out to me.

$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -online

function Hyperv-function()
{
    if ($hyperv.State -eq "Enabled")

        { 
        echo "Hyper-v Enabled"
        }

    Else

    { 

        echo "hyper-v not installed"

    }

}

If ((Hyperv-function) -eq "Hyper-v Enabled")
{
Echo "Hyper-v already Installed"
}

ElseIf ((Hyperv-function) -eq "hyper-v not installed")
{

Echo "installing Hyper-V"
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
}

Start-Sleep -s 5

$wslstate = Get-WindowsOptionalFeature -Online -FeatureName Microsoft-windows-Subsystem-Linux

Function Wsl-check()
{

If ($wslstate.State -eq "Enabled")
    {
    Echo "WSL enabled"
    }
    Else
    {
    Echo "WSL not enabled"
    }

}

If ((Wsl-check) -eq "WSL enabled")
{
Echo "WSL already enabled"
}

ElseIf ((Wsl-check) -eq "WSL not enabled")
{
Echo "Installing WSL now..."
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
}

Start-Sleep -s 5

$hypervadmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole('S-1-5-32-578')

Function hypervadminadd()
{

If ($hypervadmin -eq "True")
    {
    Echo "Enabled"
    }
    Else
    {
    Echo "Disabled"
    }

}

If ((hypervadminadd) -eq "Enabled")
{
Echo "Adding current user to Hyper-v adminstrator group now... please wait..."
([adsi]"WinNT://./Hyper-V Administrators,group").Add("WinNT://$env:UserDomain/$env:Username,user") > $Null
}

ElseIf ((hypervadminadd) -eq "Disabled")
{
Echo "Adding current user to Hyper-V member now...please wait"
([adsi]"WinNT://./Hyper-V Administrators,group").Add("WinNT://$env:UserDomain/$env:Username,user") > $Null
}

Start-Sleep -s 5

Echo "All done...."

0 Comments

Leave a Reply

Your email address will not be published.