0

几周前,我开始设置我的 MDT(Microsoft 部署工具包)自定义映像。到目前为止,几乎所有东西都运行良好,除了我最近的 Powershell 脚本,该脚本用于在没有 RSAT 工具的情况下将计算机添加到特定的安全组。我在新安装的操作系统上对其进行了测试,但我不断收到异常,如下所示的 Powershell 异常链接中所示。我并不真正喜欢 Powershell 编程,我测试了几个脚本以使其正常工作,最终我得到了这个,但我认为我没有完全掌握它。

任何帮助/建议或替代方法都非常感谢:)。

我的 Powershell 代码:

<#
PowerShell to join computer object to Active Directory Group without AD module being imported
This finds the computer object anywhere in AD and adds it to a security group in a known location
#>

#Get computer name
 $ComputerName = gc env:computername

#Check to see if computer is already a member of the group
 $isMember = new-object DirectoryServices.DirectorySearcher([ADSI]"NameofMYSecurityGroup")
 $ismember.filter = “(&(objectClass=computer)(sAMAccountName= $Computername$)(memberof=CN=Computers,DC=MY_DOMAIN,DC=LOCAL))”
 $isMemberResult = $isMember.FindOne()

#If the computer is already a member of the group, just exit.
 If ($isMemberResult) {exit}

else
#If the computer is NOT a member of the group, add it.
{
   $searcher = new-object DirectoryServices.DirectorySearcher([ADSI]"NameofMYSecurityGroup")
   $searcher.filter = “(&(objectClass=computer)(sAMAccountName= $Computername$))”
   $FoundComputer = $searcher.FindOne()
   $P = $FoundComputer | select path
   $ComputerPath = $p.path
   $GroupPath = "LDAP://CN=Computers,DC=MY_DOMAIN,DC=LOCAL"
   $Group = [ADSI]"$GroupPath"
   $Group.Add("$ComputerPath")
   $Group.SetInfo()
}

顺便说一句,它是德语,但它基本上说:

Exception calling "Add" with 1 Arguments: "Unknown Name. (Exception From HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))
AT F:\"SourcePath"
+    $Group.Add("$ComputerPath")

     +CategoryInfo          :NotSpecified: (:) [], MethodInvocationException
     +FullyQuallifiedErrord :CatchFromBaseAdapterMethodInvoke

异常链接:

Powershell 异常

4

1 回答 1

0

未经测试,但这可能会帮助您朝着正确的方向前进:

$ComputerName = $env:COMPUTERNAME
$GroupDN      = 'CN=Computers,DC=MY_DOMAIN,DC=LOCAL'

# initialize the DirectorySearcher
$root     = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root.defaultNamingContext)
$searcher.SearchScope = 'SubTree'

# Check to see if computer is already a member of the group
$searcher.Filter = "(&(objectCategory=Computer)(objectClass=User)(samaccountname=$ComputerName$)(memberof=$GroupDN))"
$isMember = $searcher.FindOne()

# If the computer is already a member of the group, just exit.
if ($isMember) { exit }

# get the computer object
$searcher.Filter = "(&(objectCategory=Computer)(objectClass=User)(samaccountname=$ComputerName$))"
$ComputerDN      = $searcher.FindOne().Properties['distinguishedname']
$ComputerObject  = [ADSI]"LDAP://$ComputerDN"

# get the group object
$GroupObject = [ADSI]"LDAP://$GroupDN"

# add the computer to the group
$GroupObject.Add($ComputerObject.AdsPath)
# no need for this $Group.SetInfo()
于 2021-07-26T15:06:48.153 回答