我如何在Powershell上recursion创build组织单位?

我正在编写一个Powershell脚本来将所有公司用户从CSV文件填充到Active Directory。

该脚本使用Powershell命令New-ADUser ,并且应该知道,对于每个用户,添加path的位置在哪里,例如:

 "OU=IT Dept,OU=Users,DC=local,DC=contoso" 

问题是:这个活动目录还没有任何用户,所以没有创build组织单元,每当我运行脚本,如果path不存在,用户不会被创build。

我查找了一个创build组织单位的命令,比如New-ADOrganizationalUnit或者dsadd ,但是他们不支持recursion创build,比如

 "OU=Helpdesk,OU=IT Dept,OU=Users,DC=local,DC=contoso" 

如果

 "OU=IT Dept,OU=Users,DC=local,DC=contoso" 

尚不存在。

有什么办法使用New-ADOrganizationalUnit

谢谢

正如Mike在评论中提到的那样,您需要逐步遍历树中的每个级别,并testingOU祖先的存在,然后从最顶层和最下层创build不存在的元素。

只要New-ADOrganisationalUnit没有-Recurse参数,这是我能想到的最优雅的方式:

 function New-OrganizationalUnitFromDN { [CmdletBinding(SupportsShouldProcess=$true)] param( [string]$DN ) # A regex to split the DN, taking escaped commas into account $DNRegex = '(?<![\\]),' # Array to hold each component [String[]]$MissingOUs = @() # We'll need to traverse the path, level by level, let's figure out the number of possible levels $Depth = ($DN -split $DNRegex).Count # Step through each possible parent OU for($i = 1;$i -le $Depth;$i++) { $NextOU = ($DN -split $DNRegex,$i)[-1] if($NextOU.IndexOf("OU=") -ne 0 -or [ADSI]::Exists("LDAP://$NextOU")) { break } else { # OU does not exist, remember this for later $MissingOUs += $NextOU } } # Reverse the order of missing OUs, we want to create the top-most needed level first [array]::Reverse($MissingOUs) # Prepare common parameters to be passed to New-ADOrganizationalUnit $PSBoundParameters.Remove('DN') # Now create the missing part of the tree, including the desired OU foreach($OU in $MissingOUs) { $newOUName = (($OU -split $DNRegex,2)[0] -split "=")[1] $newOUPath = ($OU -split $DNRegex,2)[1] New-ADOrganizationalUnit -Name $newOUName -Path $newOUPath @PSBoundParameters } } 

使用WHATIF

 # The desired resulting OU DN $DN = "OU=Helpdesk,OU=IT Dept,OU=Users,DC=local,DC=contoso" New-OrganizationalUnitFromDN $DN -WhatIf 

没有WHATIF

 # The desired resulting OU DN $DN = "OU=Helpdesk,OU=IT Dept,OU=Users,DC=local,DC=contoso" New-OrganizationalUnitFromDN $DN 

如果path中存在不存在的非OU容器,将会中断。

$NextOU.IndexOf("OU=")的输出区分大小写,对于所有小写字母将返回-1 ou= try: $NextOU.IndexOf("OU=",[StringComparison]"CurrentCultureIgnoreCase")