首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查OU是否已经存在

检查OU是否已经存在
EN

Stack Overflow用户
提问于 2022-09-15 17:05:14
回答 1查看 50关注 0票数 0

此脚本基于CSV创建OU,并将它们放入MyLab OU中,并创建2个子OU。它还检查CSV中的OU是否已经存在,然后输出它。我一直试图弄清楚如何为SubOU做到这一点,所以如果其中一个存在,另一个仍然是创建的。有人能为我指明正确的方向吗?

代码语言:javascript
复制
#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","

#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"

#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
$Name = $OU.Name 

#Check if an OU within the CSV file already exists
$Check = Get-ADOrganizationalUnit -filter * | Where-Object {$_.name -eq $OU.name} | select name

#If it does the text within the write-host is output
if ( $OU.name -eq $Check.name) {
    write-host $OU.name "OU already exists"}

#if not the OU is created, with a 2 sub ous created within it 
else{New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false

    $SubOUs = "Department1", "Department2"
    $subPath = "OU="+$OU.name+","+$ParentPath
    
    foreach ($SubOU in $SubOUs){
    New-ADOrganizationalUnit -Name $SubOU -Path $subPath -ProtectedFromAccidentalDeletion $false
    }
}

}

EN

回答 1

Stack Overflow用户

发布于 2022-09-15 20:04:05

要始终创建子of,可以在创建父of的if之外执行另一个if检查。这是我保持大多数事物不变的方法,但是改进了对OU的检查:

代码语言:javascript
复制
#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","
#Query existing OUs only once at the start
$existingOUs = Get-ADOrganizationalUnit -filter * 

#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"

#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
  # Build distinguished name
  $DN = "OU="+$OU.name+","+$ParentPath

  #check for OU in existing list
  if ($existingOUs.DistinguishedName -contains $DN) { write-host $OU.name "OU $DN already exists" }
  else { 
    New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false 
  }

  # then create 2 sub OUs within each $OU
  $SubOUs = "Department1", "Department2"
  foreach ($SubOU in $SubOUs){
    $SubDN = "OU="+$SubOU.name+","+$DN
    
    # check if sub OU exists
    if ($existingOUs.DistinguishedName -contains $SubDN) { write-host $OU.name "OU $DN already exists" }
    else { 
      New-ADOrganizationalUnit -Name $SubOU -Path $DN -ProtectedFromAccidentalDeletion $false 
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73735000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档