在创建OU之前检查OU是否存在

时间:2015-11-26 14:48:03

标签: validation powershell active-directory

function NyChildOU {
  $overOU = Read-Host "Type in the name of the parrent OU"
  $oucheck = [adsi]::Exists("LDAP://OU=$overOU,OU=PS,DC=PS,DC=local")
  if ($oucheck -eq "true") {
    $navnpaaou = Read-Host "Type in the name of the new OU"
    $oucheck2 = [adsi]::Exists("LDAP://OU=$navnpaaou,OU=$overOU,OU=PS,DC=PS,DC=local")
    if ($oucheck2 -eq "false") {
      New-ADOrganizationalUnit -Name $navnpaaou -path "OU=$navnpaaou,OU=$overOU,OU=PS,DC=PS,DC=Local"
      Write-Host "The new entry: $navnpaaou is created within $overOU"
    } else {
      Write-Host "OUen $navnpaaou do exist within $overOU"
    }
  } else {
    Write-Host "OUen $overOU doesen't exist, trie again"
  }
}

这是我的脚本,其目的是创建一个OU,除非它已经存在。我无法弄清楚我的代码有什么问题。

2 个答案:

答案 0 :(得分:3)

只需检查Get-ADOrganizationalUnit是否返回具有该专有名称的OU,否则创建它:

$parentOU = 'OU=parent,OU=PS,DC=example,DC=com'
$navnpaaou = Read-Host "Type in the name of the new OU"
$newOU = "OU=$navnpaaou,$parentOU"
if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$newOU'") {
  Write-Host "$newOU already exists."
} else {
  New-ADOrganizationalUnit -Name $navnpaaou -Path $parentOU
}

答案 1 :(得分:0)

我尝试了接受的答案,发现如果OU不存在则会抛出异常。以下函数尝试检索OU,捕获抛出的错误(如果它不存在),然后创建OU。

function CreateOU ([string]$name, [string]$path, [string]$description) {
    $ouDN = "OU=$name,$path"

    # Check if the OU exists
    try {
        Get-ADOrganizationalUnit -Identity $ouDN | Out-Null
        Write-Verbose "OU '$ouDN' already exists."
    }
    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
        Write-Verbose "Creating new OU '$ouDN'"
        New-ADOrganizationalUnit -Name $name -Path $path -Description $description
    }
}

CreateOU -name "Groups" -path "DC=ad,DC=example,DC=com" -description "What a wonderful OU this is"