PowerShell 中的 "Set-Content" 是否保留文件访问权限?
Does "Set-Content" in PowerShell keep the File Access rights?
我计划通过 PowerShell 更新一些文件。 Set-Content 会保留访问权限 (ACL) 还是我必须明确备份和恢复这些权限?
Set-Content
(和Add-Content
)和Out-File
/>
(>>
)不重新创建一个现有的目标文件,他们替换(追加)它的内容,所以它的ACLs被保留。
您可以使用以下示例代码验证这一点:
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
上面的结果如下所示,表明自定义 ACL 即使在用 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
我计划通过 PowerShell 更新一些文件。 Set-Content 会保留访问权限 (ACL) 还是我必须明确备份和恢复这些权限?
Set-Content
(和Add-Content
)和Out-File
/>
(>>
)不重新创建一个现有的目标文件,他们替换(追加)它的内容,所以它的ACLs被保留。
您可以使用以下示例代码验证这一点:
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
上面的结果如下所示,表明自定义 ACL 即使在用 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