chmod function for PowerShell

Narek picture Narek · Sep 13, 2012 · Viewed 31.9k times · Source

I was looking around to understand how to chmod (change permissions of a file) a file on Windows 7 Power Shell. So I have found different (wired for me, because I am used to simple chmod command) code snippets and wondering would't it be simple to wrap that wired commands in a chmod function and write it on in a $profile file of Power Shell. I guess this is what many ex-linux shell, but now power shell users would like to have for changing permissions of a file.

I am new to Power Shell. Please help me with the code.

Answer

JPBlanc picture JPBlanc · Sep 14, 2012

Here is an example with the native way, using ACL and ACE. You have to build your own functions arround that.

# Get the Access Control List from the file
# Be careful $acl is more a security descriptor with more information than ACL
$acl = Get-Acl "c:\temp\test.txt"


# Show here how to refer to useful enumerate values (see MSDN)
$Right = [System.Security.AccessControl.FileSystemRights]::FullControl
$Control = [System.Security.AccessControl.AccessControlType]::Allow

# Build the Access Control Entry ACE 
# Be careful you need to replace "everybody" by the user or group you want to add rights to
$ace = New-Object System.Security.AccessControl.FileSystemAccessRule ("everybody", $Right, $Control)

# Add ACE to ACL
$acl.AddAccessRule($ace)

# Put ACL to the file
Set-Acl "c:\temp\test.txt" $acl
(Get-Acl "c:\temp\test.txt").access
Read-Host "--------- Test Here --------------"

# Remove ACE from ACL
$acl.RemoveAccessRule($ace)
Set-Acl "c:\temp\test.txt" $acl
(Get-Acl "c:\temp\test.txt").access