Adding a domain user to a local group using PowerShell

Following on from the fun of giving write permissions on a folder to a user, today’s installment covers adding a domain user to a local group.

Specifically, the group “Performance Log Users”, which allows a process to use (rather than create) perf counters.

function Add-UserToPerformanceLogUsersGroup($user, $session) {  
  Invoke-Command -Args $user -Session $session -ErrorAction Stop -ScriptBlock {
    param($user)
    
    $groupName = "Performance Log Users"
    $group = [ADSI]("WinNT://$env:COMPUTERNAME/$groupName,group")
    # check if user is already a member
    $members = @($group.psbase.Invoke("Members"))
    $matches = $members | where { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -eq $user.split("\")[1] }
    
    if ($matches -eq $null) {
      Write-Host "Adding $user to $groupName group"   
      $user = $user.replace("\", "/")
      $group.add("WinNT://$user,user")
    }
  }
}

Caveat: the user specified is assumed to be a fully qualified DOMAIN\User, hence the unpleasant string manipulation.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s