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

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

Stack Overflow用户
提问于 2015-11-26 22:48:03
回答 2查看 15.8K关注 0票数 4
代码语言:javascript
复制
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,除非它已经存在。我就是找不出我的代码出了什么问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-26 23:58:20

只需检查Get-ADOrganizationalUnit是否返回具有可分辨名称OU,否则创建该OU:

代码语言:javascript
复制
$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
}
票数 5
EN

Stack Overflow用户

发布于 2017-11-01 01:33:16

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

代码语言:javascript
复制
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"
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33941460

复制
相关文章

相似问题

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