Creating a “Hyper-V Administrators” local group through PowerShell

Creating a “Hyper-V Administrators” local group through PowerShell

  • Comments 3


After writing my script to allow a non-administrative user to control Hyper-V – I started thinking about how it would be nice if I could easily add and remove users from being Hyper-V administrators – without having to run a script each time.  Which lead to this:

$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
   }
 
# Create "Hyper-V Administrators" group
$LocalComputer = [ADSI] "WinNT://$env:computername"
$HvAdminGroup = $LocalComputer.create("Group", "Hyper-V Administrators")
$HvAdminGroup.setinfo()
 
# Get the SID for the newly created group
$HvAdminGroupSID = (gwmi Win32_Group | ?{$_.Name -eq "Hyper-V Administrators"}).sid
 
# Add current user to Hyper-V Administrators group
$fixedUserName = $myWindowsID.Name -replace "\\","/"
$HvAdminGroup.add("WinNT://$env:computername/$fixedUserName")
 
# Get the current AzMan store location from the registry
$AzManStoreLocation = (Get-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization").StoreLocation
 
# Open the AzMan store
$AzManStore = new-object -ComObject "AzRoles.AzAuthorizationStore"
$AzManStore.Initialize(2, $AzManStoreLocation)
 
# Handle the default Hyper-V AzMan store and the SCVMM AzMan store
if (@($AzManStore.Applications | ? {$_.Name -contains "Hyper-V services"}).count -eq 1)
   {
   $HyperVAzManStore = $AzManStore.OpenApplication("Hyper-V services")
   }
elseif (@($AzManStore.Applications | ? {$_.Name -contains "Virtual Machine Manager"}).count -eq 1)
   {
   $HyperVAzManStore = $AzManStore.OpenApplication("Virtual Machine Manager")
   }
else
   {
   Write-Host "Unable to find AzMan application group."
   Write-Host -NoNewLine "Press any key to continue..."
   $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
   exit
   }
 
# Get the administrator role from the Hyper-V service in the AzMan store
$HyperVAdministratorsRole = $HyperVAzManStore.OpenRoleAssignment("Administrator")
 
# Add the Hyper-V Admin group to the AzMan store
$HyperVAdministratorsRole.AddMember($HvAdminGroupSID)
$HyperVAdministratorsRole.Submit()

What this script does is to create a local user group – called “Hyper-V Administrators” – and then configures that group to have full access to Hyper-V (it also adds the current user as a member of the “Hyper-V Administrators” group).  After running this script you can make other users Hyper-V Administrators by just adding them to the group (with no need to run the script again).  Note that the same caveats apply to this script as did to yesterdays script:

  • It must run as administrator – and will elevate itself if you run it without administrative privilege.
  • This script talks to AzMan COM objects – which means that it cannot be run remotely, and must be run directly on the Hyper-V server.
  • This script will handle the default Hyper-V and SCVMM authorization configurations – but if you run the script on a standalone Hyper-V server, which you later use SCVMM to manage – you will need to run the script again.

Cheers,
Ben

Attachment: AzManGroup.zip
Leave a Comment
  • Please add 8 and 4 and type the answer here:
  • Post
  • The script formatting in the post seems to go wrong after the -replace "\\","/"., and the strings from lines further down the script have moved to the end of the -replace line.

  • I have to agree with Stephen.  I'm getting an error that I'll copy below.   sadly I've not gotten into PS yet, so don't know enough to make a guess at how to correct the script.

    Unexpected token 'WinNT://$env:computername/$fixedUserName")HKLM:\SOFTWARE\Micr

    osoft\Windows NT\CurrentVersion\Virtualization"' in expression or statement.

    At C:\smag\HVadmingroup.ps1:45 char:161

    + $fixedUserName = $myWindowsID.Name -replace "\\","/"WinNT://$env:computername

    /$fixedUserName")HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualizat

    ion" <<<< ).StoreLocationAzRoles.AzAuthorizationStore"Hyper-V services"}).count

    -eq 1)Hyper-V services")Virtual Machine Manager"}).count -eq 1)Virtual Machine

    Manager")Unable to find AzMan application group."Press any key to continue..."

    NoEcho,IncludeKeyDown")Administrator")

       + CategoryInfo          : ParserError: (WinNT://$env:co...Virtualization":

      String) [], ParseException

       + FullyQualifiedErrorId : UnexpectedToken

  • Yikes!  I do not know how the sample code got that badly mangled. It should be fixed now.  Either way - if you grap the .ZIP file attached to the post it should have the correct code.

    Cheers,

    Ben

Page 1 of 1 (3 items)