如何解决通过 Powershell 将 PC 添加到 AD 中的安全组,而无需安装 RSAT
几周前,我开始设置我的 MDT(Microsoft 部署工具包)自定义映像。到目前为止,几乎一切正常,除了我最近的 Powershell 脚本,该脚本用于将计算机添加到没有 RSAT 工具的特定安全组。我在新安装的操作系统上对其进行了测试,但我不断收到异常,如下所示的 Powershell 异常链接。我不是很喜欢 Powershell 编程,我测试了几个脚本来让它工作,最后我得到了 this 一个,但我想我没有完全掌握它。
非常感谢任何帮助/建议或替代方法:)
我的 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=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
异常链接:
解决方法
未经测试,但这可能会帮助您朝着正确的方向前进:
$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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。