2015-11-26 79 views
1
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是否存在

+1

它有什麼問題?當你運行它會發生什麼?你在期待什麼? –

+0

它認識到父OU存在,但堅持孩子已經存在 – Freshman

+0

嘗試將-eq「true」和-eq「false」改爲'-eq $ true'和'-eq $ false' –

回答

2

簡單的檢查,如果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 
} 
+0

這個工程,但我不想代碼返回錯誤味精如果子單元已經存在:) – Freshman

+0

由於某種原因我用if-sets檢查不起作用 – Freshman

+0

@Freshman好吧,如果你想要一個錯誤信息:只需添加一條錯誤信息。 –

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" 
相關問題