Change permissions in a fileshare poweshell

I have a fileshare that has many folders and subfolders, some subfolders have there own permissions and some inherit, but for all folders I want to replace whatever permissions that might be set in the folder with read permissions only. I have tried this

  $SiteString=[String]$SiteURL          

  $pos=$SiteString.LastIndexOf("/")        

  $Site=$SiteString.Substring($pos+1)          

  $parent=((get-item$Folder).parent).Fullname     

  $AllFolders=Get-ChildItem-Recurse-Path$Folder|?{$_.psIsContainer -eq$True} 

  $FilesInRoot=Get-ChildItem-Path$Folder|?{$_.psIsContainer -eq$False}      

   $acl=get-acl$Folder       

   Foreach($usrin$acl.access){                       

$acl.RemoveAccessRule($usr)                       

$rule=New-ObjectSystem.Security.AccessControl.FileSystemAccessRule($usr.IdentityReference,"Read","none","none","Allow")

$Acl.AddAccessRule($rule)

}                   

$acl|Set-Acl            

}catch{continue}                       

#Loop through all folders (recursive) that exist within the folder supplied by the operator                        

foreach($CurrentFolderin$AllFolders){                   

$FolderRelativePath=($CurrentFolder.FullName).Substring($Folder.Length)

$FileSource=$Folder+$FolderRelativePath

try{                      

$acl=get-acl$FileSource                  

Foreach($usrin$acl.access){                       

$acl.RemoveAccessRule($usr)                       

$rule=New-ObjectSystem.Security.AccessControl.FileSystemAccessRule($usr.IdentityReference,"Read","none","none","Allow")

$acl.AddAccessRule($rule)                     

}                   

$acl|Set-Acl                    

}catch{continue}

}


                                    


                

            

but unfortunately it doesn't do what I want it to do, it doesn't replace the permissions just adds them to what is already there and with folders with their own permissions it just throws an error

Set-Acl : The process does not possess the 'SeSecurityPrivilege' privilege which is required for this

operation.

At C:\Users\dah\Documents\RobIACASMigration\AcasFinishMigration.ps1:68 char:28

+                     $acl | Set-Acl

+                            ~~~~~~~

    + CategoryInfo          : PermissionDenied: (\\grape\Documen...kjkjkjkjkjkjjkj:String) [Set-Acl], Privileg

   eNotHeldException

    + FullyQualifiedErrorId : System.Security.AccessControl.PrivilegeNotHeldException,Microsoft.PowerShell.Com

   mands.SetAclCommand

 



  • Edited by bended 17 hours 9 minutes ago
July 25th, 2015 10:02am

Are you running powershell with elevated privileges? (Run as Administrator)
Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 10:06am

I am running powerhsell as an admin
July 25th, 2015 10:09am

Can you fix your post.  It is unreadable.

You cannot post colorized code as it wil not format correctly.

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 10:21am

You are not running as an administrator with full privileges.  Please look up and understand UAC.

https://www.google.com/?gws_rd=ssl#newwindow=1&q=uac

July 25th, 2015 10:23am

Your post is badly formated!

But from what you told us so far, it seems a common error. As the error message says, the privilege is not held by the user. Here is an older post that treats this subject with an interesting solution.

wizend

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 10:30am

If you could actually see the code you would see that there are many weird errors and syntax issues as well as overall design and execution.

The scrip is pasted to gether and edited by someone who does not know basic PowerShell.

July 25th, 2015 10:55am

Set-Acl is causing the error message about not having the 'SeSecurityPrivilege' (technically this isn't the Set-Acl Cmdlet's fault, but instead PowerShell's FileSystem provider). That privilege is only needed if you're trying to modify the System ACL (used for auditing), and you're not doing that in this case. You actually see this error when the AreAccessRulesProtected on the on-disk security descriptor and AreAuditRulesProtected properties on the in memory security descriptor don't match. Here's a recreation of the issue:

# Run this in a non-elevated prompt!

# First, create a dummy file
$FilePath = "$env:temp\test_file.txt"
"This is a test" | Out-File -FilePath $FilePath

# This should work just fine
$SD = Get-Acl $FilePath  # Get securty descriptor
$SD | Set-Acl            # Set SD w/o making any changes

# Notice this returns $true
(Get-Acl $FilePath).AreAccessRulesProtected -eq $SD.AreAuditRulesProtected

# Now disable DACL inheritance:
$SD = Get-Acl $FilePath
$SD.SetAccessRuleProtection($true, $true)

# This is still true, so Set-Acl will work:
(Get-Acl $FilePath).AreAccessRulesProtected -eq $SD.AreAuditRulesProtected
$SD | Set-Acl

# Now the same command that was run earlier will fail:
$SD = Get-Acl $FilePath  # Get securty descriptor
$SD | Set-Acl            # Set SD w/o making any changes


Running as an elevated admin will hide the issue (you don't see an error, but the SACL will be overwritten, which is a very bad thing if you're trying to audit your filesystem).

The best thing to do is always use the file/folder's SetAccessControl() method. It would look something like this:

$SD = Get-Acl $FilePath
(Get-Item $FilePath).SetAccessControl($SD)

I suggest always avoiding Set-Acl while working with the file system. If you'd like to fix get it fixed, you can vote the Connect bugs here and here up.

All that aside, replacing all ACEs like you're asking isn't that hard to do. Of course, you need to be EXTREMELY CAREFUL when trying to do something like that. Just eyeballing it, it looks like your code might actually do what you want (assuming the formatting errors were introduced when you pasted your code in this post) if you run elevated or change your Set-Acl calls to SetAccessControl() calls. There are at least three things that do stand out as needing some attention, though:

  1. The code will probably take a 'Deny' ACE and turn it into an ACE granting 'Read' access.
  2. The code doesn't take inheritance and propagation flags into account (it will create ACEs that apply directly to the folders, which isn't the default for a folder)
  3. The code will probably create explicit ACEs for each inherited ACE, which will create a mess

What about something like this?

$VerbosePreference = "Continue"
dir C:\path\to\folder -Recurse -Directory | ForEach-Object {
    $FSO = $_
    Write-Verbose ("Current file system object: {0}" -f $FSO.FullName)
    try {
        $SD = $FSO | Get-Acl
    }
    catch {
        Write-Error ("Error getting security descriptor for '{0}': {1}" -f $FSO.FullName, $_.Exception.Message)
        return
    }

    # Just look for explicit ACEs:
    foreach ($Ace in $SD.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])) {
        if ($Ace.AccessControlType -ne "Allow") { continue }  # I'm assuming you don't want to loosen Deny ACEs

        Write-Verbose ("    Found ACE granting '{0}' access to '{1}'; replacing with 'Read' access" -f $Ace.FileSystemRights, $Ace.IdentityReference)

        # Create an identical ACE, except with 'Read' access only (this preserves the inheritance and propagation flags)
        $ReadAce = New-Object System.Security.AccessControl.FileSystemAccessRule(
            $Ace.IdentityReference,
            "Read",
            $Ace.InheritanceFlags,
            $Ace.PropagationFlags,
            $Ace.AccessControlType
        )

        # SetAccessRule will actually replace the existing ACE. No need to call Remove() then Add()
        $SD.SetAccessRule($ReadAce)
    }

    Write-Verbose "    Saving changes..."

    # You'll have to uncomment this line:
#    $FSO.SetAccessControl($SD)
}

Notice that the last line that actually makes changes is commented out. It won't save anything unless you remove the '#', but please make sure you've tested this thoroughly before running it in a production environment.

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 9:56pm

Never though that a set-acl would over-write a SACL.  Are you sure about that?  I havenever seenit happen.

The audit SACL seems to be maintained oover Get-Acl and Set-Acl.  If you are doing a complete replace of the ACl structures by creating a DACL and its ACEs then it would over-write the existing SACL and DACL.  This is not normally how we do things.

July 25th, 2015 10:08pm

To be sure I just tested this.  Changing the DACL with Set-Acl does not alter the SACL.  After Set-Acl the SAL is the same as it was before.

Why do you think this is true?

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 10:20pm

To be sure I just tested this.  Changing the DACL with Set-Acl does not alter the SACL.  After Set-Acl the SAL is the same as it was before.

Why do you think this is true?

July 25th, 2015 10:48pm

I just did that and it doesn't do that for me. Perhaps your system  has an issue.

I set a folder to audit for everyone and did exactly what you just sis here.  The SACL wasn't changed.

Are you saying that this only happens when the SACL is inherited and not when it is direct?

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 11:34pm

I just did that and it doesn't do that for me. Perhaps your system  has an issue.

I set a folder to audit for everyone and did exactly what you just sis here.  The SACL wasn't changed.

Are you saying that this only happens when the SACL is inherited and not when it is direct?

July 25th, 2015 11:54pm

I am running WMF 5 April on Windows 8.1.

Name                           Value
----                           -----
PSVersion                      5.0.10105.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   10.0.10105.0
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3

PS C:\scripts> (gwmi win32_operatingsystem).CAption
Microsoft Windows 8.1 Pro with Media Center

Free Windows Admin Tool Kit Click here and download it now
July 26th, 2015 12:01am

I am running WMF 5 April on Windows 8.1.

Name                           Value
----                           -----
PSVersion                      5.0.10105.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   10.0.10105.0
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3

PS C:\scripts> (gwmi win32_operatingsystem).CAption
Microsoft Windows 8.1 Pro with Media Center

July 26th, 2015 12:11am

Ok - I remember that bug.  It only occurs if you are running elevated. When not elevated the SACL is not written.

Yes - that will happen.  Sorry it took me so long too remember that issue.  The key is that it only happens when elevated.

Thanks for the push.

Free Windows Admin Tool Kit Click here and download it now
July 26th, 2015 12:30am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics