-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADImport.py
85 lines (73 loc) · 3.03 KB
/
ADImport.py
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
# Import the Active Directory module
Import-Module ActiveDirectory
# Function to create a new user and assign permissions
function New-ADUserWithPermissions {
param (
[string]$FirstName,
[string]$LastName,
[SecureString]$UserPassword,
[string]$OU,
[string]$Group,
[string]$PermissionsFolderPath
)
# Construct the user's attributes
$UserName = "$FirstName.$LastName"
$DisplayName = "$FirstName $LastName"
$UserPrincipalName = "[email protected]"
$Email = "[email protected]"
try {
# Create the new user in the specified OU
New-ADUser -Name $DisplayName `
-GivenName $FirstName `
-Surname $LastName `
-UserPrincipalName $UserPrincipalName `
-SamAccountName $UserName `
-EmailAddress $Email `
-Path $OU `
-AccountPassword (ConvertTo-SecureString $UserPassword -AsPlainText -Force) `
-Enabled $true
# Add the new user to the specified AD group
Add-ADGroupMember -Identity $Group -Members $UserName
# Enable the user account
Enable-ADAccount -Identity $UserName
# Assign NTFS permissions to the user on the specified folder (Modify Permissions Example)
if ($PermissionsFolderPath) {
$acl = Get-Acl $PermissionsFolderPath
$permission = "DOMAIN\$UserName", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
Set-Acl $PermissionsFolderPath $acl
Write-Host "Permissions for $UserName set on $PermissionsFolderPath"
}
Write-Host "User $DisplayName created and added to the $Group group with permissions."
} catch {
Write-Host "Error: $_"
}
}
# Function to revoke permissions and disable user account upon termination
function Revoke-ADUserPermissionsOnTermination {
param (
[string]$UserName,
[string]$Group,
[string]$PermissionsFolderPath
)
try {
# Remove user from the specified AD group
Remove-ADGroupMember -Identity $Group -Members $UserName -Confirm:$false
# Revoke NTFS permissions from the user on the specified folder
if ($PermissionsFolderPath) {
$acl = Get-Acl $PermissionsFolderPath
$accessRule = $acl.Access | Where-Object { $_.IdentityReference -like "*\$UserName" }
if ($accessRule) {
$acl.RemoveAccessRule($accessRule)
Set-Acl $PermissionsFolderPath $acl
Write-Host "Permissions for $UserName revoked on $PermissionsFolderPath"
}
}
# Disable the user account
Disable-ADAccount -Identity $UserName
Write-Host "User $UserName account disabled and permissions revoked."
} catch {
Write-Host "Error: $_"
}
}