0

I plan to update some files via PowerShell. Will Set-Content keep the access rights (ACL) or do I have to backup and restore these rights explicitly?

Martini Bianco
  • 1,484
  • 1
  • 13
  • 23
  • 2
    Have you.. tried? – Maximilian Burszley Sep 14 '18 at 22:42
  • 2
    `Set-Content` does not change file ACLs just contents. Why do you think it might? – Matt Sep 15 '18 at 00:26
  • Sorry, I haven't tried. Because, at the time, I was not able to test it on the files I needed to it, because I wrote the script for my colleague, as I had not the right myself to change the files. I thought I ask, because someone probably already knew the answer. Also it was important, that the ACLs were not changed, So I asked beforehand. – Martini Bianco Sep 17 '18 at 18:22

1 Answers1

1

Set-Content (and Add-Content) and Out-File / > (>>) do not recreate an existing target file, they replace (append to) its contents, so its ACLs are preserved.

You can verify this with the following example code:

Push-Location $env:TEMP

Remove-Item tmp.txt -EA SilentlyContinue

# Create file 'tmp.txt with default ACL.
'original content' | Set-Content tmp.txt

# Modify the ACL to allow the Guests groups read access.
$acl = Get-Acl tmp.txt
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule Guests, Read, Allow))
Set-Acl tmp.txt $acl

'ACL *before* Set-Content:'
(Get-Acl tmp.txt).Access.IdentityReference | Out-Host


# Use Set-Content to replace the existing content.
'new content' | Set-Content tmp.txt

# Verify that the file's ACL hasn't changed.
'ACL *after* Set-Content:'
(Get-Acl tmp.txt).Access.IdentityReference | Out-Host

Remove-Item tmp.txt

The above yields something like the following, showing that the custom ACL was preserved even after replacing the file's content with Set-Content:

ACL *before* Set-Content:

Value
-----
BUILTIN\Guests
NT AUTHORITY\SYSTEM
BUILTIN\Administrators
WS1\jdoe


ACL *after* Set-Content:

Value
-----
BUILTIN\Guests
NT AUTHORITY\SYSTEM
BUILTIN\Administrators
WS1\jdoe
mklement0
  • 382,024
  • 64
  • 607
  • 775