-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateFolderAndPermissions.ps1
More file actions
73 lines (62 loc) · 2.32 KB
/
createFolderAndPermissions.ps1
File metadata and controls
73 lines (62 loc) · 2.32 KB
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
#*****************************************************************
#
# Script Name: createFolderAndPermissions.ps1
# Version: 1.0
# Author: John G@llo
# Date: September 23, 2014
#
# Description: Used to create folder on a given location and grant
# Domain Admins Full Control and grant specific access (e.g. Modify)
# to a user(optional)
#
# Mandatory parameters:
# FolderPath
# Folder
#
# Optional parameters (in case you want to grant access to a user besides Domain Admins)
# UserName
# Permissions
#
# Use Cases:
# 1) Create Home Directories and grant the user access, as well as Domain Admins
# C:\> createFolderAndPermissions.ps1 -FolderPath X:\ -Folder "john" -UserName "john" -Permission Modify
#
# 2) Create a directory and grant access to only domain admins
# C:\> createFolderAndPermissions.ps1 -FolderPath 'G:\teamfolders' -Folder "myteam"
#
#*****************************************************************
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$FolderPath,
[Parameter(Mandatory=$True)]
[string]$Folder,
[Parameter(Mandatory=$False)]
[string]$UserName,
[Parameter(Mandatory=$False)]
[string]$Permission
)
# Variables
$MyDomain = 'CPGNY'
# The below code should only run when there is a new folder, otherwise it can
# change permissions on existing folders which may be undesirable
if(Test-Path -path "$FolderPath\$Folder"){
write-host "You attempted to create and change permissions on an existing folder"
write-host "$FolderPath\$Folder already exists"
Exit
}
# Create a new folder under given path
New-Item -Name $Folder -ItemType Directory -Path $FolderPath -ErrorAction Stop | Out-Null
# Gather existing ACL
$ACL = Get-Acl "$FolderPath\$Folder"
# Remove inheritance
$ACL.SetAccessRuleProtection($true, $false)
# Remove existing ACL's
$ACL.Access | ForEach { [Void]$ACL.RemoveAccessRule($_) }
# Prepare new ACL's
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("$MyDomain\Domain Admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
if($UserName -and $Permission){
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("$MyDomain\$UserName","$Permission", "ContainerInherit, ObjectInherit", "None", "Allow")))
}
# Set new ACL's
Set-Acl "$FolderPath\$Folder" $ACL