Search code examples
powershelliis-7powershell-1.0

Creating Local Group and Adding A User To The Group


I have a PowerShell script that builds IIS sites and configures settings. Most of it works as expected except for a function to either add a domain user to a specific local group or if the group is not there to create the group than add the user. I get this error when adding to the group:

Exception calling "add" with "1" argument(s): "A member could not be added to or removed from the local group because the member does not exist.

I have PowerShell v1.0 so I do not have access to the Microsoft.PowerShell.LocalAccounts module so using Add-LocalGroupMember and New-LocalGroup are not an option.

function addEventLogWriter($appPoolUser) {
    $user = $appPoolUser
    $group = "Event Log Writers"
    $description = "Members of this group can write event logs from local machine" 

    #try{
    $groupObj =[ADSI]"WinNT://./$group,group" 
    $membersObj = @($groupObj.psbase.Invoke("Members")) 
    $members = ($membersObj | foreach {
        $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
    })

    Write-Output "Adding Service Account To Event Log Writers..."
    if ($members -contains $user) {
        Write-Host "$user already exists in the group $group..."
    } else {
        $groupObj.add("WinNT://./$user,user")
        Write-Output "$user added to $group"
    }
}

At the moment the group 'Event Log Writers' has been created but in the case it is not (ie: new server builds etc..), I would like my function check to make sure the group is there, if not, create the group than add the user.


Solution

  • The issue is because ADSI requires a slash instead of a backslash like a typical username.

    Also, how the group membership returns, in this case, it drops the domain name, so we have to split out the username when seeing if it exists.

    So if your $appPoolUser is a credential object with the full username:

    function addEventLogWriter($appPoolUser) {
        $AdsiUsername = $appPoolUser.replace('\','/')
        $user = $appPoolUser.Split('\')[1]
    
        $group = "Event Log Writers"
        $description = "Members of this group can write event logs from local machine" 
    
        #try{
        $groupObj =[ADSI]"WinNT://./$group,group" 
        $membersObj = @($groupObj.psbase.Invoke("Members")) 
        $members = ($membersObj | foreach {
            $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
        })
    
        Write-Output "Adding Service Account To Event Log Writers..."
        if ($members -contains $user) {
            Write-Host "$user already exists in the group $group..."
        } else {
            $groupObj.add("WinNT://./$AdsiUsername,user")
            Write-Output "$user added to $group"
        }
    }