Powershell: Apply owner to multiple files and folders per username - powershell

We have a server that houses the My Documents folder for all our users. Some of the folder owner changed to administrator. I am trying to devise a PowerShell script that goes to each user's root my documents folder and applies the user as the owner for all the sub folders and files with in it. Is this Possible?
I have the following from a previous script that attempted to set the user as full permissions per each my document root folder:
$FolderPath = "E:\mydocuredir\"
$MyDocsMain = Get-ChildItem -Path $FolderPath -Directory
Get-ChildItem -Path $FolderPath -Directory | ForEach-Object{
$HomeFolders = Get-ChildItem $FolderPath $_.Name -Directory
$Path = $HomeFolders.FullName
$Acl = (Get-Item $Path).GetAccessControl('Access')
$Username = $_.Name
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule($Username, 'FullControl', 'ObjectInherit', 'InheritOnly', 'Allow')
$Acl.SetAccessRule($Ar)
Set-Acl -path $Path -AclObject $Acl
}

Firstly ensure that the share and root folder permissions for redirected folders follow best practice.
I would use the NTFSSecurity PS Module (blog on its use). This module has commands that are much easier to understand as they follow they way your would set permissions via the GUI.
$FolderPath = "E:\mydocuredir"
Get-ChildItem -Path $FolderPath -Directory | ForEach-Object{
Add-NTFSAccess -Path $_.FullName -Account "domain\$($_.Name)" -AccessRights FullControl -AppliesTo ThisFolderSubfoldersAndFiles
}
To set Owner, replace the Add-NTFSAccess command with:
Set-NTFSOwner -Path $_.FullName -Account "domain\$($_.Name)"

Related

Powershell for adding permissions to folders without inheritance

We have a giant folder located at "D:\Economy" with hundreds of subfolders. We have a new employee which needs permissions for ALL those folders. Unfortunately there are alot of folders without inheritance, so when I add permissions on D:\Economy\ it doesnt apply to all folders.
Ive found many scrips which lists all the folders, but I can't figure out how to also apply permissions to them.
For instance, this command works for finding folders:
DIR "D:\Economy" -directory -recurse | GET-ACL | where {$_.Access.IsInherited -eq $false}
This command works for setting permissions, but it only applies to those with inheritance enabled:
path = "D:\Economy\"
$acl = Get-Acl $path
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("MYCOMPANY\firstname.surname","Modify","Allow")
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
So how do I merge those together?
This is something I wrote up but it doesnt work:
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("MYCOMPANY\firstname.surname","Modify","Allow")
$acl.SetAccessRule($AccessRule)
dir "D:\Economy\" -Directory -recurse | get-acl | Where {$_.AreAccessRulesProtected} | set-acl "D:\Economy\"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("MYCOMPANY\firstname.surname","Modify","Allow")
Get-ChildItem "D:\Economy\" -Directory -Recurse | %{
$acl = Get-Acl -Path $_.FullName
if ($acl.AreAccessRulesProtected) {
$acl.AddAccessRule($AccessRule)
$acl | Set-Acl -Path $_.FullName
}
}

Create Subfolders using Powershell

Ok, looking for some assistance with Powershell. I need to create a subfolder with the same name in about 200 folders in a directory. So far I have this:
$folder = NewFolderName
new-item -type directory -path \\servername\directory\directory\$folder -Force
Will this work to create the single folder in all 200 folders?
Try the following code snippet:
$parent = '\\servername\directory'
$folder = 'NewFolderName'
Get-ChildItem -Path $parent -Directory |
ForEach-Object {
New-Item -WhatIf -Type Directory -Path (
Join-Path -Path $_.FullName -ChildPath $folder) -Force
}
Remove the risk mitigation parameter -WhatIf no sooner than debugged…

Remove NTFS permissions of a user in all sub-directories

I am writing a PowerShell script which would delete a specific user from all sub-directories.
Below script only removes the permission from the folder but I want to remove permission from all sub-folders as well.
$acl = get-acl c:\temp
$accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule ("domain\user","Read",,,"Allow")
$acl.RemoveAccessRuleAll($accessrule)
Set-Acl -Path "c:\temp" -AclObject $acl
You are only setting the acl of the root folder. Set-Acl by itself does not allow you to propagate to subfolders.
Note that that might not be what you want anyway. You want to remove a rule from all folders instead of replacing the acls on all subfolders with the acl of your root folder.
Safer would be to get the acl of each subfolder, remove the rule and set the acl of each subfolder.
icaclscudo's to Ansgar might be better for this task. A Powershell way might be as follows
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("domain\user","Read",,,"Allow")
$root = 'c:\temp'
#(Get-Item $root) + #(Get-ChildItem $root -Recurse -Directory) | Foreach-Object {
$acl = Get-Acl $_.FullName
$acl.RemoveAccessRuleAll($accessrule)
Set-Acl $_.FullName -AclObject $acl -WhatIf
}
$Path = "c:\temp\"
$User = "admin"
$Account = new-object system.security.principal.ntaccount($User)
$ACL = Get-Acl -path $Path
$ACL.PurgeAccessRules($Account)
$ACL | Set-Acl -path $Path -Verbose
gci -Recurse -Path $Path -Directory | %{
$ACL = Get-Acl -path $_.FullName
$ACL.PurgeAccessRules($Account)
$ACL | Set-Acl -path $_.FullName -Verbose
}

Set folder permission with Powershell

Example of the goal, the crossout is the same user.
I've created a script that creates a folder based on users SAMaccount and it works like it should, it also gives full control on the folder, not inherited.
My goal is to set another set of full control permissions for the same user, but inherited from the "top folder" and the full control should should only applie to "this folder only"
My script so far is below:
$users = Get-ADUser -filter * -SearchBase "OU=Test,OU=Users,OU=Bla Groups,DC=Bla,DC=local" |
Select-Object -ExpandProperty sAMAccountName
ForEach($user in $users)
{
$newPath = Join-Path "c:\Temp\Test" -childpath $user
New-Item $newPath -type directory -Force
$acl = (Get-Item $newpath).GetAccessControl('Access')
$permission = "Bla.local\$user","FullControl",#("ContainerInherit","ObjectInherit"),"None","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
$acl | Set-Acl $newpath
}

Script Won't Set Permissions with Wildcard

I have a PowerShell script that I wrote to create a subfolder "Admin", if it doesn't already exist, in over 4000 folders in a shared directory. After creating the subfolders I need the permissions of the subfolders to only be for a specific group within the domain. I get no errors, other than the folder already exist errors on the subfolder, but I let the script run for 12 hours and it never completed. I stopped the script to find that all the Admin subfolders were created but the permissions were not set.
If I take out the * wildcard in the $folder add input a folder name it works perfectly. How can I get it work with the * wildcard so I don't have to manually enter over 4000 folder names?
Here is my script:
# If the folder for Equipment Images does not exist, make a new one and set the correct permissions.
$Location = "E:\Images\Equipment\*\"
$file = "E:\Images\Equipment\*\Admin"
foreach ($_ in (Get-ChildItem E:\Images\Equipment\*\)) {
if (($_.PSIsContainer -AND $_.name -eq "Admin")-eq $false) {
New-Item -Path $location -Name "Admin" -ItemType directory
$errorActionPreference = "continue"
}
$folder = "E:\Images\Equipment\*\Admin"
$acl = Get-Acl $folder
if ($acl.AreAccessRulesProtected) {
$acl.Access | % {$acl.purgeaccessrules($_.IdentityReference)}
} else {
$isProtected = $true
$preserveInheritance = $false
$acl.SetAccessRuleProtection($isProtected, $preserveInheritance)
}
$account = "recoequip\folder sales group"
$rights = [System.Security.AccessControl.FileSystemRights]::FullControl
$inheritance = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
$propagation = [System.Security.AccessControl.PropagationFlags]::None
$allowdeny = [System.Security.AccessControl.AccessControlType]::Allow
$dirACE = New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$rights,$inheritance,$propagation,$allowdeny)
$ACL.AddAccessRule($dirACE)
Set-Acl -aclobject $ACL -Path $folder
Write-Host $folder Permissions added
}
Just don't use the wildcard with any Acl cmdlets, I don't think that will work.
Set the permission on a single folder in the loop before, or if you have to do it later, just loop through all the folders and set the permissions on all admin folders individually, one by one.
Some tips:
Start with a small sub-set of the 400 folders for testing, and Write-Host the currently processed folder so you can see the progress.
Code sample:
Get-ChildItem E:\Images\Equipment\ -Directory -Filter "admin" -Recurse | ForEach-Object {
$acl = Get-Acl $_.FullName
... # do your permission stuff
}