Powershell taking ownership of folder before set-acl - powershell

Can I take over ownership and then set-acl to a folder? I have a folders.txt file where I have the location of the folder.
For Example:
D:\Dept\CC\NorthRiver\16-17\StaffAdministration
Then I am creating a new year of the previous year folder structure and copying the rights and permissions of the previous years folders to the new folder years matching folder. I ran into an issue though because of ownership of the folder. If I am not the owner I can not duplicate the permissions of certain folders and I receive Set-ACL : The security identifier is not allowed to be the owner of this object. Is there any way around this?
I tried adding the line (to change the owner to me but that did not work either):
get-item $currentFolder.Replace("16-17", "15-16") | set-owner -Account 'VDB-TST1\Administrators'
Does anyone have any ideas of how I may accomplish this?
This is the full script I have:
Function Get-FileName{
[CmdletBinding()]
Param(
[String]$Filter = "|*.*",
[String]$InitialDirectory = "C:\")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
#Get and Set the ACL to the new years folder structure
foreach ($currentFolder in (GC (Get-FileName -InitialDirectory $env:USERPROFILE\Desktop -Filter "Text files (*.txt)|*.txt|All files (*.*)|*.*"))) {
md $currentFolder # Create Folder
get-item $currentFolder.Replace("16-17", "15-16") | set-owner -Account 'VDB-TST1\Administrators'
Get-ACL $currentFolder.Replace("16-17", "15-16") | Set-ACL $currentFolder
}

I think you are running into the same limitations of Set-ACL and Get-ACL described in this post. try changing
Get-ACL $currentFolder.Replace("16-17", "15-16") | Set-ACL $currentFolder
to
(Get-Item $currentFolder.Replace("16-17", "15-16")).GetAccessControl('Access') | Set-ACL $currentFolder
As an alternative you can use robocopy to copy the ntfs permissions from one directory and then apply them to another.
robocopy $currentFolder.Replace("16-17", "15-16") $currentfolder /copy:S /SECFIX
Hope this helps.

The Set-ACL cmdlet native to powershell is pretty terrible. I would suggest using the NTFS module that is available. I have tried playing with Set-ACL several times and it always wastes more of my time rather than actually being useful.

Related

Can't see parent directory when assigning subdirectory permissions

Sorry everyone, for bothering you. Currently I have a command line to enforce user permissions already working on the specified directory but I need your help on how to be able to see the higher level directory when the user accesses it. Because now, when the user accesses normally, he will not see a higher-level directory to access, he must access the available path, so it is very inconvenient. I just need to see the folders to access without editing or see another subfolder inside.
$acl = Get-Acl 'D:\TEST'
$path = "D:\TEST"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("test.ktdv","write","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("test.ktnb","read","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
Get-ChildItem -Path "$Path" -Recurse -Force |
Where-Object { ($_.Name -eq 'New Folder' -or $_.Name -eq 'B') } |
Set-Acl -Aclobject $acl -Verbose

Home Drive Creation Issue

I have PowerShell a script to create a new user's home drive and I am using below command:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath
It's creating the home drive for the user but the user isn't able to access it.
One more thing, I can copying the created home drive manually from AD console and again pasting it and clicking on apply then it works fine.
Set-ADUser will only modify the user object in ActiveDirectory; security permissions on the folder itself is an additional step.
FileSystemRights Enumeration: MSDN
It is not sufficient to simply use Set-ADUser, expecting full end to end creation of a fully functioning home directory; we must set permissions on the folder in question, including any inheritance flags.
There's a few steps to accomplish this, but simply stated:
We need to get the current access control list (ACL)
We need to add our desired permissions to said ACL
We need to write the new ACL, combining both the pre-existing and new permissions.
As you may have guessed:
Get-ACL
Set-ACL
We can so something like this:
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
If you're feeling creative, you can also combine some of the flags into an array:
$InheritanceFlag = #('ContainerInherit','ObjectInherit')
Please note this code is NOT tested and to validate before executing in any environment.

Cannot access folder after modifying ACL with Powershell

I am trying to modify folder ACL through Powershell with following code. First i want to clear ACL and stop inheritance and then add only specific users to it.
This seem working fine, but if i trying to open that folder it gives following error.
What is wrong with the script?
$acl = Get-ACL -Path "c:\mydata"
$acl.SetAccessRuleProtection($True, $False)
$acl | Set-Acl -Path "c:\mydata"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("DBUSER","FullControl","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("ADMIN","FullControl","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$acl | Set-Acl -Path "c:\mydata"
You are setting an empty ACL, then trying to make changes when you no longer have permissions. Normally, you should be getting an error on the second Set-ACL
$acl | Set-Acl $path
Set-Acl : The process does not possess the 'SeSecurityPrivilege' privilege which is required for this operation.
Instead, try setting the ACL only once:
$path = 'c:\mydata'
$acl = Get-ACL $path
$rule1 = [System.Security.AccessControl.FileSystemAccessRule]::new(
"DBUSER","FullControl","ContainerInherit,ObjectInherit","None","Allow" )
$rule2 = [System.Security.AccessControl.FileSystemAccessRule]::new(
"ADMIN","FullControl","ContainerInherit,ObjectInherit","None","Allow" )
$acl.AddAccessRule($rule1)
$acl.AddAccessRule($rule2)
# Flush the inherited permissions, and protect your new rules from overwriting by inheritance
$acl.SetAccessRuleProtection($True, $False)
# Output what the new access rules actually look like:
$acl.Access | ft
$acl | Set-Acl $path
If you need to keep the existing permissions, then use $acl.SetAccessRuleProtection($True, $True) instead.
Finally, make sure you're actually logged in as either DBUSER or ADMIN when testing access to the folder.

powershell add user permission to a folder in windows server

So I've got the next path: C:\folder1\folder2\fileName. Looking in the security tab on the C:\folder1 there is Alice username with full permissions. But going to the C:\folder1\folder2\fileName Alice isn't there yet. How can I insert with powershell v2 Alice member recursively in C:\folder1 so that all the files under root C:\folder1 will also have the same Alice username set with full permissions.
I've tried:
$acl = Get-Acl C:\folder1
$permission = "domain\Alice","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl C:\folder1
But it doesn't seem to apply for the C:\folder1\folder1\fileName. Guess I'm trying to apply permissions for Alice, which doesn't exist yet in the last fileName item.
As you can see in the FileSystemAccessRule documentation, the class has a property for inheritance.
You have to add the property to your $permission
$permission = "domain\Alice",
"FullControl",
[System.Security.AccessControl.InheritanceFlags]"ContainerInherit",
[system.security.accesscontrol.PropagationFlags]"None",
"Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
You could also recursively add the permissions by getting all child items with the Get-ChildItems cmdlet and piping them to the Set-Acl cmdlet like they have done in an examle in the documentation on microsoft site here: Set-Acl. Look at "Example 3: Apply a security descriptor to multiple files" or read below (copied from the page):
PS C:\> $NewAcl = Get-Acl File0.txt
PS C:\> Get-ChildItem -Path "C:\temp" -Recurse -Include "*.txt" -Force | Set-Acl - AclObject $NewAcl
These commands apply the security descriptors in the File0.txt file to all text files in the C:\Temp directory and all of its subdirectories.
The first command gets the security descriptor of the File0.txt file in the current directory and uses the assignment operator (=) to store it in the $NewACL variable.
The first command in the pipeline uses the Get-ChildItem cmdlet to get all of the text files in the C:\Temp directory. The Recurse parameter extends the command to all subdirectories of C:\temp. The Include parameter limits the files retrieved to those with the ".txt" file name extension. The Force parameter gets hidden files, which would otherwise be excluded. (You cannot use "c:\temp*.txt", because the -Recurse parameter works on directories, not on files.)
The pipeline operator (|) sends the objects representing the retrieved files to the Set-Acl cmdlet, which applies the security descriptor in the AclObject parameter to all of the files in the pipeline.
In practice, it is best to use the Whatif parameter with all Set-Acl commands that can affect more than one item. In this case, the second command in the pipeline would be "Set-Acl -AclObject $NewAcl -WhatIf". This command lists the files that would be affected by the command. After reviewing the result, you can run the command again without the Whatif parameter.
This is an example using ".txt" files but can be modified to apply to directories as well.

Using PowerShell to grant security rights to multiple folders.

We have an in-house application that creates a folder, with 8 sub-folders, whenever a new project is started (keeping the same file structure in every folder). Our fileserver sets the security to the top level folder, breaking any specific sub-folder rights.
I'm looking at using aThis System.IO.FileSystemWatcher to automate the PowerShell, once the folders have been created.
The PowerShell I'm looking at using is:
New-Item F:\Engineering Projects\TPS\Documents\ –Type Directory
Get-Acl F:\Engineering Projects\TPS\Documents\ | Format-List
$acl = Get-Acl F:\Engineering Projects\TPS\Documents\
$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 F:\Folder $acl
Get-Acl F:\Folder | Format-List
I'm not very experienced with PowerShell, Exchange things being the main area where I've experienced it. Obviously that script is more of a generic starting point for me; my question is, would I run this script multiple times (for each folder requiring specific permissions), or can I incorporate multiple folder permissions within one script?