Advertisement
captio27

Admin group membership switch powershell script

Jun 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. [CmdletBinding()]
  2. param($user)
  3.  
  4. # This checks if the shell is an admin shell, otherwise summons the script in an admin shell
  5. If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
  6. {  
  7.     $arguments = "& '" + $myinvocation.mycommand.definition + "'"  
  8.     Start-Process powershell -Verb runAs -ArgumentList ($arguments, [Security.Principal.WindowsIdentity]::GetCurrent().Name)
  9.     Break
  10. }
  11. else
  12. {
  13.     $user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
  14. }
  15.  
  16. # Running as an admin shell from this point bellow
  17.  
  18. $group = [ADSI]"WinNT://$($user.Substring(0,$user.IndexOf('\')))/Administrators,group"
  19. $user = $user.Replace("\","/")
  20.  
  21. # Tries to add the current user to the admin group, if an exception it thrown, it means the user is already admin, so we remove it instead.
  22. try{
  23.     $group.Add("WinNT://$user,user")
  24.     Write-Host "Added $user to administrators group"
  25. }
  26. catch{
  27.     $group.Remove("WinNT://$user,user")
  28.     Write-Host "Removed $user from administrators group"
  29. }
  30. sleep 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement