【问题标题】:Check if OU exists before creating it在创建之前检查OU是否存在
【发布时间】:2015-11-26 14:48:03
【问题描述】:
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,除非它已经存在。我就是想不通我的代码出了什么问题。

【问题讨论】:

  • 这有什么问题?当你运行它时会发生什么?你在期待什么?
  • 它承认父OU存在,但坚持认为孩子已经存在
  • -eq "true"-eq "false" 更改为-eq $true-eq $false
  • 你在这两个地方都改了吗? $true -eq "true" 将按预期工作,但 $false -eq "false" 不会
  • 哦,$false 可能是我的问题?抱歉,我对此很陌生,我知道错误处理非常多样化

标签: validation powershell active-directory


【解决方案1】:

只需检查 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
}

【讨论】:

  • 这行得通,但如果 subOU 已经存在,我不希望代码返回错误消息 :)
  • 由于某种原因,我对 if-sets 的双重检查不起作用
  • @Freshman 好吧,如果你想要一条错误消息:只需添加一条错误消息。
【解决方案2】:

我尝试了接受的答案,发现如果 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"

【讨论】:

  • 作为说明,我认为您可以只使用 -ErrorAction SilentlyContinue,但这不适用于 AD PowerShell cmdlet,因此此答案效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2013-09-03
  • 1970-01-01
  • 2015-03-28
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多