创建本地组并将用户添加到该组

Creating Local Group and Adding A User To The Group

我有一个构建 IIS 站点和配置设置的 PowerShell 脚本。它的大部分功能都按预期工作,除了将域用户添加到特定本地组的功能,或者如果该组不在那里创建组而不是添加用户。添加到组时出现此错误:

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.

我有 PowerShell v1.0,所以无法访问 Microsoft.PowerShell.LocalAccounts 模块,因此无法使用 Add-LocalGroupMemberNew-LocalGroup

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

目前组 'Event Log Writers' 已经创建,但如果没有(即:新服务器构建等),我希望我的功能检查以确保该组存在,如果没有,创建组而不是添加用户。

问题是因为 ADSI 需要斜杠而不是像典型用户名那样的反斜杠。

另外,组成员关系如何returns,在这种情况下,它会删除域名,因此我们必须在查看用户名是否存在时将其拆分出来。

因此,如果您的 $appPoolUser 是具有完整用户名的凭据对象:

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