1

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 :)

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@user1595214 Update is here :)
feel free to accept my answer when the code works and if it doesn't , please let me in touch, I'll help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.