Yesterday, I told you about how it was now easier to allow a non-administrative user to control Hyper-V.  This is nice – but it does mean that this script that I blogged about 4 years ago no longer works.  Here is a new one:

$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
 
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   {
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
   clear-host
   }
else
   {
   # We are not running "as Administrator" - so relaunch as administrator
 
   # Create a new process object that starts PowerShell
   $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
 
   # Specify the current script path and name as a parameter
   $newProcess.Arguments = $myInvocation.MyCommand.Definition;
 
   # Indicate that the process should be elevated
   $newProcess.Verb = "runas";
 
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
 
   # Exit from the current, unelevated, process
   exit
   }
 
# Prompt for the virtual machine to use
$Domain = Read-Host "Specify the domain of the user to add to Hyper-V Administrators (use $($env:ComputerName) for this computer)"
 
# Prompt for the path to export to
$User = Read-Host "Specify the username of the user to add to Hyper-V Administrators"
 
$HvAdmins = [ADSI]"WinNT://$env:COMPUTERNAME/Hyper-V Administrators,group"
$HvAdmins.Add("WinNT://$($Domain)/$($user),user")

This script will add any user you specify to the local “Hyper-V Administrators” group.

Cheers,
Ben