-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add-NewOrganizationalUnit.ps1
103 lines (87 loc) · 2.83 KB
/
Add-NewOrganizationalUnit.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Function Add-NewOrganizationalUnit
{
<#
.SYNOPSIS
Create a new Organizational Unit
.DESCRIPTION
Create a new Organizational Unit, query the PDC as primary server
Active Directory CMDLets are needed.
.PARAMETER Name
The name of the new Organizational Unit.
.PARAMETER Path
Specifies the OU were to create the new Organizational Unit.
.EXAMPLE
Add-NewOrganizationalUnit -Name 'OU Name'
.EXAMPLE
Add-NewOrganizationalUnit -Name 'OU Name' -Path 'OU=My Location,OU=Servers,DC=prutser,DC=me'
.INPUTS
String
.OUTPUTS
Creates a new Organizational Unit in Active Directory
Status is outputted to screen
.NOTES
Author: Wouter de Dood
Website:
Twitter: @WMouter
#>
[cmdletbinding()]
param (
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string]$Name,
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string]$Path = 'OU=Customers,OU=Sales,DC=prutser,DC=me' #Set this path as default
)
Begin
{
$ErrorActionPreference = 'Stop'
Try
{
Import-Module ActiveDirectory
}
Catch
{
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Error] Module not loaded, ActiveDirectory Module is mandatory."
Throw
}
$Identity = "OU=$Name,$Path"
[string]$Server = (Get-ADDomainController -Service PrimaryDC -Discover).HostName #Target PDC of current domain
}
Process
{
$ErrorActionPreference = 'Stop'
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Action] Create Organizational Unit: $Name in $Path"
Try
{
Get-ADOrganizationalUnit -Identity $Identity -Server $Server | Out-Null
$ouCreate = $false
}
Catch
{
$ouCreate = $true
}
if ($ouCreate -eq $true)
{
Try
{
New-ADOrganizationalUnit -Name $Name -Path $Path -Server $Server
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Status] Created"
}
Catch
{
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Error] Not created!"
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Error] $($_.Exception.Message)"
}
}
else
{
Write-Output "[$(Get-Date -UFormat "%Y-%m-%d %H:%M:%S")] - [Status] No need to create already exists"
}
}
End
{
Remove-Variable ouCreate,Name,Path,Server,Identity
}
} #end function Add-NewOrganizationalUnit