2013-05-06 72 views
1

我正在使用以下功能將用戶添加到本地用戶組。我需要將用戶數組添加到我的機器上的本地組。將用戶添加到本地用戶組

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") 
    } 
} 

[email protected]("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") 

我收到以下錯誤:

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

我是新來的PowerShell。請幫助:)

回答

2

的問題是在這裏

-GroupName:"Comserver Consumer", -Userarr 

逗號是PowerShell的一個數組的分隔符。

你遇到的問題是,你分開逗號的參數,但PowerShell使它成爲哪個空間。

看看這個問題的更多信息: How do I pass multiple parameters into a function in PowerShell?

/更新

這裏是代碼

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][email protected]("Username", "NETWORK SERVICE", "LOCAL SERVICE","SYSTEM") 
AddUsersToGroup -MachineName "localhost" -GroupName "Testgroup" -Users $UserArray 

請嘗試一下

+0

感謝您的答覆,等待爲修復:) – user1595214 2013-05-06 11:45:41

+0

@ user1595214更新在這裏:) – Solaflex 2013-05-06 11:54:02

+0

隨時接受我的答案時的代碼如果沒有,請讓我聯繫,我會幫你 – Solaflex 2013-05-06 12:04:19