How to create folder, share and apply NTFS permissions - powershell

Being a total novice of Powershell I am trying to put together a script using the below script from various TechNet script examples:
$FolderPath = 'c:\folder'
$Shares=[WMICLASS]'WIN32_Share'
$ShareName='Home$'
New-Item -type directory -Path $FolderPath
$Shares.Create($FolderPath,$ShareName,0)
$Acl = Get-Acl $FolderPath
$Acl.SetAccessRuleProtection($True, $False)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Administrators','FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')
$Acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Users","Read", "ContainerInherit, ObjectInherit", "None", "Allow")
$Acl.AddAccessRule($rule)
Set-Acl $FolderPath $Acl
Get-Acl $FolderPath | Format-List
The above script works quite well in terms of creating the folder and sets the permissions as:
Share: Everyone "Full"
NTFS: Users "Read"
I can't seem to figure out how to apply the below permissions, I am struggling with the parameters for System.Security.AccessControl.FileSystemAccessRule to set the below NTFS permissions.
Set Share permissions:
Authenticated Users: change
Administrators: full control
Set NTFS permissions:
Administrators: full control
SYSTEM: full control
Authenticated users: list folder/read data & create folders/append data, this folder only
Creator/Owner: full control, subfolders and files only
Any help will be greatly appreciated.
Thanks in advance.

You could have solved this yourself if you had tried to search. I've created an answer for share permissions earlier here, and NTFS permissions are easily found too. Try this:
#Local path
$FolderPath = 'c:\folder'
$Shares=[WMICLASS]'WIN32_Share'
#Share name
$ShareName='Home$'
#Create folder
New-Item -type directory -Path $FolderPath
#Create share rights
#Define a trustee (person/group to give access right)
$trustee = ([wmiclass]‘Win32_trustee’).psbase.CreateInstance()
$trustee.Domain = "NT Authority"
$trustee.Name = “Authenticated Users”
#Define an access control entry (permission-entry)
$ace = ([wmiclass]‘Win32_ACE’).psbase.CreateInstance()
#Modify-rights
$ace.AccessMask = 1245631
#Inheritance for folders and files
$ace.AceFlags = 3
$ace.AceType = 0
#Assign rights to Authenticated users ($trustee)
$ace.Trustee = $trustee
$trustee2 = ([wmiclass]‘Win32_trustee’).psbase.CreateInstance()
$trustee2.Domain = "BUILTIN" #Or domain name
$trustee2.Name = “Administrators”
$ace2 = ([wmiclass]‘Win32_ACE’).psbase.CreateInstance()
#Full control
$ace2.AccessMask = 2032127
$ace2.AceFlags = 3
$ace2.AceType = 0
#Assign rights to Administrators ($trustee2)
$ace2.Trustee = $trustee2
#Create ACL/security descriptor. This is the security-definitions that you set on the share.
$sd = ([wmiclass]‘Win32_SecurityDescriptor’).psbase.CreateInstance()
#Specify that a DACL (ACL/security/permissions) are available, so the share isn't set to full access for everyone
$sd.ControlFlags = 4
#Add our rules
$sd.DACL = $ace, $ace2
#Set Administrators ($trustee2) as owner and group of ITEM (will be the share)
$sd.group = $trustee2
$sd.owner = $trustee2
#Create share with the security rules
$shares.create($FolderPath, $ShareName, 0, 100, "Description", "", $sd) | Out-Null
#Get NTFS permissiongs
$Acl = Get-Acl $FolderPath
#Disable inheritance and clear permissions
$Acl.SetAccessRuleProtection($True, $False)
#Define NTFS rights
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('Administrators','FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')
$Acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('SYSTEM','FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')
$Acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Authenticated Users",#("ReadData", "AppendData", "Synchronize"), "None", "None", "Allow")
$Acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule('CREATOR OWNER','FullControl','ContainerInherit, ObjectInherit', 'InheritOnly', 'Allow')
$Acl.AddAccessRule($rule)
#Save ACL changes (NTFS permissions)
Set-Acl $FolderPath $Acl | Out-Null
#Show ACL so user can verify changes
Get-Acl $FolderPath | Format-List

Related

how to change specific folder permissions with powershell no GUI [duplicate]

I am trying to use the "default" options in applying folder permissions; by that, I mean that using the "Full Controll, Write, Read, etc" in the 'Properties' for a folder.
The following script works to add the user in, but it applies "Special Permissions" - not the ones with the tick boxes for the ones visible in the properties menu of the folder:
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule ("user","FullControl","Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
What am I doing wrong please?
Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").
$Acl = Get-Acl "\\R9N2WRN\Share"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl
According to this topic
"when you create a FileSystemAccessRule the way you have, the
InheritanceFlags property is set to None. In the GUI, this
corresponds to an ACE with the Apply To box set to "This Folder Only",
and that type of entry has to be viewed through the Advanced
settings."
I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it.
This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Another example using PowerShell for set permissions (File / Directory) :
Verify permissions
Get-Acl "C:\file.txt" | fl *
Apply full permissions for everyone
$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"
Screenshots:
Hope this helps
In case you need to deal with a lot of folders containing subfolders and other recursive stuff. Small improvement on #Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line
This One work for me
$path = "C:\test"
$name = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$acl = Get-Acl "C:\test"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($name,"FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\test"
Get-ChildItem -Path "$path" -Recurse -Force | Set-Acl -aclObject $acl -Verbose
$path = "C:\DemoFolder"
$acl = Get-Acl $path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Attribs = $username, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AcessControl.FileSystemAccessRule($Attribs)
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
Get-ChildItem -Path "$path" -Recourse -Force | Set-Acl -aclObject $acl -Verbose

Powershell to set Read&Execute permission on a folder for Authenticated users

Im newbie in powershell and trying to figure out a way to set folder permissions for Authenticated Users. I want to remove all permissions for this user except Read&Execute.
I've tried to code below but it doesnt quite give the result I want:
$folder = 'C:\folder'
#remove inheritance
$acl = Get-ACL -Path $folder
$acl.SetAccessRuleProtection($True, $True)
Set-Acl -Path $folder -AclObject $acl
#set folder permissions to Read&Execute
$user = New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList #([System.Security.Principal.WellKnownSidType]::AuthenticatedUserSid, $null)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule)
Set-Acl -Path $folder -AclObject $acl

"Set-Acl" not working when owner is not administrator

Getting the below error when trying to set permissions via PowerShell.
Set-Acl : The security identifier is not allowed to be the owner of this object.
I am trying to assign modify permission to folders and files within a folder recursively using PowerShell. The script works fine on folders where administrator is owner, but throws an error when the administrator is not owner:
$location = "E:\Data\Path_of_folder"
$group = "SecurityGroup_RW"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule ($group, "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
$folders = Get-Childitem $location -Recurse | Where-Object {$_.PSISContainer}
foreach ($folder in $folders) {
$path = $folder.FullName
$acl = (Get-Item $path).GetAccessControl('Access')
$acl.SetAccessRule($rule)
Set-Acl $path $acl
}
I should be able to set the permissions for all folders, not just the folders for which Administrator is the owner.

Grant domain user/group privilege to folders recursively

Written below code to grant domain user privilege to folder in windows 2016. In output I can see that the user is added in folder permissions but did not add any permission though I mentioned to give full control access.
$rule=new-object System.Security.AccessControl.FileSystemAccessRule("domain\group","FullControl","Allow")
foreach ($file in $(Get-ChildItem "G:\usr" -recurse))
{
$acl=get-acl $file.FullName
$acl.SetAccessRule($rule)
set-acl $File.Fullname $acl
}
For recursive permissions you need to set ContainerInherit,ObjectInherit
Here is an example (Note it's not my code):
$Path = "C:\temp\New folder"
$Acl = (Get-Item $Path).GetAccessControl('Access')
$Username = "Domain\User"
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$Acl.SetAccessRule($Ar)
Set-Acl -path $Path -AclObject $Acl
For more details take a look at http://www.tomsitpro.com/articles/powershell-manage-file-system-acl,2-837.html

Powershell script creating home folder for user and setting permissions

I am doing a powershell script which creates new domain user accounts in AD, and also creating home directories in the file server with relevant permissions.
My problem is I cannot get the permissions set.
In the code below, my_fileServer is the file server name; sso means single-sign-on id, which in the test code below is set to "user9999".
Any help is greatly appreciated!
Set-Variable homeDir -option Constant -value "\\my_fileServer\Users"
Set-Variable sso -option Constant -value "user9999"
# If the folder for the user does not exist, make a new one and set the correct permissions.
if ( (Test-Path "$homeDir\$sso") -eq $false)
{
try
{
$NewFolder = New-Item -Path $homeDir -Name $sso -ItemType "Directory"
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount "my_full_domain_name\$sso"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$ACL = get-acl -Path $NewFolder
$ACL.AddAccessRule($objACE)
$objReturn = Set-ACL -Path "$homeDir\$sso" -AclObject $ACL
$objReturn
}
catch
{
$msg = $_
$msg
}
}
The home folder gets created OK, but when I check the permissions for the user, no box is ticked.
The problem is your inhertiance. You are not allowing the permission to be inherited on subfolders and files(items he owns in his folder). That's why you don't see the permissions(only "Special Permission") in the basic security window. If you open "Advanced Security Settings" you will see that the user has full control OVER THIS folder, and not the contents. As long as you add permissions(with inheritance) for CREATOR OWNER so the owner get's access on to items, I think you'll be fine. However, you could fix it already now like this:
$InheritanceFlag = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
Unless there are special requirements, you should give users complete access over his folder(full inheritance). Full solution with fixed inheritance (I also cleaned up your Set-ACL path and removed unnecessary returnobject):
try
{
$NewFolder = New-Item -Path $homeDir -Name $sso -ItemType "Directory"
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl,Modify,ReadAndExecute,ListDirectory,Read,Write"
$InheritanceFlag = #([System.Security.AccessControl.InheritanceFlags]::ContainerInherit,[System.Security.AccessControl.InheritanceFlags]::ObjectInherit)
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount "my_full_domain_name\$sso"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)
$ACL = Get-Acl -Path $NewFolder
$ACL.AddAccessRule($objACE)
Set-ACL -Path $NewFolder.FullName -AclObject $ACL
}
I sadly can't vote up, but I agree with both answers above(Graimer and C.B.), the actual answer is a combination of both.
- You need to check permissions in the "advanced" window
- Even though your code "works", without inheritance your users won't be able to do much in the folder you assign them.
All the permissions are correctly set as 'Special Permmissions', you can check clicking on Advanced and look at 'Authorization' tab.
Keep it simple, do it with less... What you missed is the SetAccessRuleProtection function.
Here's the code that will give you the ticks that you want.
if (-not (Test-Path "$homeDir\$sso"))
{
$acl = Get-Acl (New-Item -Path $homedir -Name $sso -ItemType Directory)
# Make sure access rules inherited from parent folders.
$acl.SetAccessRuleProtection($false, $true)
$ace = "$domain\$sso","FullControl", "ContainerInherit,ObjectInherit","None","Allow"
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($ace)
$acl.AddAccessRule($objACE)
Set-ACL -Path "$homeDir\$sso" -AclObject $acl
}