几个星期前,我开始设置我的MDT(Microsoft Deployment Toolkit)自定义映像。到目前为止,除了我最近的Powershell脚本(用于在没有RSAT工具的情况下将计算机添加到特定的安全组)之外,几乎所有东西都运行良好。我在新安装的操作系统上测试了它,但我一直得到异常,如下面的Powershell异常链接所示。我不是很喜欢Powershell编程,我测试了几个脚本来让它工作,我最终用了这个,但我想我没有完全掌握它的窍门。
任何帮助/建议或替代方案都是非常感谢的:)。
My Powershell Code:
<#
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异常
未经测试,但这可能会帮助您找到正确的方向:
$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()