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 {
    $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("\", "/")

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

Creating perf counters using IronRuby

Custom performance counters are an extremely useful tool for monitoring production applications.

But before you can use them, you need to create them!

Some of our deployment scripts are written in PowerShell, which means you can use all the power of the BCL. But others are written in Rake/Ruby, where you can’t.

Thankfully the IronRuby project gives you the best of both worlds:

include System::Diagnostics

def delete_counters(category_name)
	if PerformanceCounterCategory.Exists(category_name)
		puts "Deleting counter category: #{category_name}"
		PerformanceCounterCategory.Delete category_name

def create_counter(counter_name)
	puts "Creating counter for #{counter_name}"
	counter =
	counter.CounterName = counter_name
	counter.CounterType = PerformanceCounterType.NumberOfItems32

def create_counter_category(category_name, counters)
	puts "Creating counter category: #{category_name}"
	PerformanceCounterCategory.Create(category_name, "", PerformanceCounterCategoryType.SingleInstance, counters)

category_name = "My Service"


puts "Creating counter creation data"
counters =
counters.Add create_counter("A Counter")
counters.Add create_counter("Another Counter")
create_counter_category(category_name, counters)