Skip to content

Instantly share code, notes, and snippets.

@bobalob
Last active December 21, 2016 11:59
Show Gist options
  • Save bobalob/908ba5869d002b643de97f0c9693c273 to your computer and use it in GitHub Desktop.
Save bobalob/908ba5869d002b643de97f0c9693c273 to your computer and use it in GitHub Desktop.
Param(
[Parameter(Mandatory=$true)]$Domain,
[Parameter(Mandatory=$true)]$User,
[Parameter(Mandatory=$true)]$computerName
)
$WindowsAccount = Get-WmiObject -Class Win32_Account -Filter "Domain='$($domain)' and Name='$($user)'"
if ($WindowsAccount) {
#### Add user/group into the local group
$Group = "WinRMRemoteWMIUsers__" #This group only seems to be on 2012 R2 (Not on 2016) - change to "Remote Management Users" for 2016
$LocalGroup = [ADSI]"WinNT://$computerName/$Group,group"
$LocalGroup.psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
#### Add user/group into the local Hyper-V Admins group
$Group2 = "Hyper-V Administrators"
$LocalGroup2 = [ADSI]"WinNT://$computerName/$Group2,group"
$LocalGroup2.psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
#### Add user/group to required WMI namespace
#Get Existing Permission Descriptor from object
$namespace = "root/InterOp"
$securityDescriptor = (Invoke-WmiMethod -Namespace $namespace `
-Path "__systemsecurity=@" -ComputerName $computerName -Name GetSecurityDescriptor).Descriptor
#Create a new Permission with magic numbers
$newDacl = (New-Object System.Management.ManagementClass("win32_Ace")).CreateInstance()
$newDacl.AccessMask = 33 #Enable Account and Remote Enable
$newDacl.AceType = 0x0 #Allow
$newDacl.AceFlags = 0
#Add AD user/Group to the permission
$trustee = (New-Object System.Management.ManagementClass("win32_Trustee")).CreateInstance()
$trustee.SidString = $WindowsAccount.Sid
$newDacl.Trustee = $trustee
#Put the permission back in the Permission Descriptor
$securityDescriptor.DACL += $newDacl.psobject.immediateBaseObject
#Set the descriptor back on the object
$Result = Invoke-WmiMethod -Namespace $namespace `
-Path "__systemsecurity=@" -ComputerName $computerName -Name SetSecurityDescriptor `
-ArgumentList $securityDescriptor.psobject.immediateBaseObject
} else {
Write-Warning "Can't find AD account specified"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment