user1595214
user1595214

Reputation: 551

Add users to Local User Group

I am using following function to add Users to local user group.I need to Add an array of users to a local group on my machine.

function AddUsersToGroup([string]$MachineName,[string]$GroupName,[String[]]$Userarr)
{
    write-host 'write: $Userarr'
    Foreach($s in $Userarr)
    {
        write-host $s
    }
    $objOU = [ADSI]"WinNT://$MachineName/$GroupName,group"  
    Foreach($User in $Userarr)
    {
        $objOU.add("WinNT://$MachineName/$User,user")
    }  
} 

$UserArray=@("Administrator", "NETWORK SERVICE", "LOCAL SERVICE","SYSTEM")
AddUsersToGroup -MachineName:"localhost" -GroupName:"Comserver Consumer",-Userarr:@("Administrator", "NETWORK SERVICE", "LOCAL SERVICE","SYSTEM")
AddUsersToGroup -MachineName:"localhost" -GroupName:"Comserver Consumer",-Userarr:@("Administrator", "NETWORK SERVICE", "LOCAL SERVICE","SYSTEM")

I am getting the following error:

The following exception occurred while retrieving member "add":
The group name could not be found.

I am new to powershell. Please help :)

Upvotes: 1

Views: 2813

Answers (1)

Solaflex
Solaflex

Reputation: 1432

The issue is here

-GroupName:"Comserver Consumer", -Userarr

A comma is for powershell the delimiter for an array.

The problem you had was, that you seperatet the parameters which a comma, but PowerShell makes it which space.

Take a look to this Question for more informations: How do I pass multiple parameters into a function in PowerShell?

/Update

Here is the Code

function AddUsersToGroup([string]$MachineName,[string]$GroupName,[Array]$Users)
{


    $Group = [ADSI]"WinNT://$MachineName/$GroupName,group"   


    Foreach($User in $Users)
    {
        Write-Host $User
        $Group.Add("WinNT://$User,user")    
    }  
} 


[Array]$UserArray=@("Username", "NETWORK SERVICE", "LOCAL SERVICE","SYSTEM")
AddUsersToGroup -MachineName "localhost" -GroupName "Testgroup" -Users $UserArray

Please try it out

Upvotes: 3

Related Questions