简体   繁体   中英

Does “Set-Content” in PowerShell keep the File Access rights?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM