In the previous tip we explained why accessing local group members will not always work with built-in cmdlets like Get-LocalGroupMember, and ways to work around it using the old (but still functional) ADSI interface.

If you’d like to build solutions on top of this, you may be wondering how local accounts can be added to or removed from groups, and how you can enable and disable local Administrator accounts.

Here are a couple of useful lines of code that illustrate the approaches. You can use these lines stand-alone or integrate them into your own script logic.

# these examples use the data below - adjust to your needs
# DO NOT RUN THESE LINES UNLESS YOU CAREFULLY
# REVIEWED AND YOU KNOW WHAT YOU ARE DOING!

# use local machine
$ComputerName = $env:computername
# find name of local Administrators group
$Group = ([Security.Principal.SecurityIdentifier]'S-1-5-32-544').Translate([System.Security.Principal.NTAccount]).Value.Split('\')[-1]
# find name of local Administrator user
$Admin = Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount = TRUE and SID like 'S-1-5-%-500'"
$UserName = $Admin.Name
# examples

# find all local groups
$computerObj = [ADSI]("WinNT://$ComputerName,computer")
$computerObj.psbase.children | 
  Where-Object { $_.psbase.schemaClassName -eq 'group' } | 
  Select-Object -Property @{N='Name';E={$_.Name[0]}}, 
    Path, 
    @{N='Sid';E={[Security.Principal.SecurityIdentifier]::new($_.objectSid.value,0).Value}} 
  


# find members of local admin group
$computerObj = [ADSI]("WinNT://$ComputerName,computer")
$groupObj = $computerObj.psbase.children.find($Group,  'Group') 
$groupObj.psbase.Invoke('Members') | 
    ForEach-Object { $_.GetType().InvokeMember('ADspath','GetProperty',$null,$_,$null) }

# add user to group/remove from group
$computerObj = [ADSI]("WinNT://$ComputerName,computer")
$groupObj = $computerObj.psbase.children.find($Group,  'Group') 
# specify the user or group to add or remove
$groupObj.Add('WinNT://DOMAIN/USER,user')
$groupObj.Remove('WinNT://DOMAIN/USER,user')

# enabling/disabling accounts
$computerObj = [ADSI]("WinNT://$ComputerName,computer")
$userObj = $computerObj.psbase.children.find($UserName,  'User')
#enable
$userObj.UserFlags=$userObj.UserFlags.Value -band -bnot 512
$userObj.CommitChanges()

#disable
$userObj.UserFlags=$userObj.UserFlags.Value -bor 512
$userObj.CommitChanges()




Twitter This Tip! ReTweet this Tip!

Anonymous