Friday, March 29, 2013

Powershell Script DIY: Permissions

One of the most frustrating things with computers is permissions.  Not being able to access a file can quite often put a full stop to your Powershell adventures.  Microsoft has made this easy by giving us the ACL commandlets for our purpose today we will use these two commandlets:


The object is to take the contents of the Foo directory, which has the owner of Greg Foo and replace the permissions with administrator.  We start by defining variable.  First we need to find an object that we defiantly have permissions to.  The desktop is an excellent choice as we can read, write, and it most definitely exists for 99% of users. So we start with our variable and the Get-ACL command:

                $ACL = Get-ACL

We need to define the location we are pulling our permissions from so we are going to use the $home environmental variable.  This variable will return the path of the current working profile.  For me it is “C:\Documents and Settings\Administrator”.  This is not good enough.  We need the desktop so we append the “\Desktop” child directory to it.  Because we have a variable in the quotations we need to use double quotes otherwise Powershell will return the variable name:

                $ACL = Get-ACL “$home\Desktop

Now that the desired permissions are defined, we need to define what we want to apply them to.  For this we need the mighty Get-Childitem commandlet, and define our object as "C:\Foo"

                Get-Childitem “C:\Foo”

Because we want ALL Items in this folder, we need to tell Powershell to look in all subsequent folders with the “-recurse” operator and to select all hidden folders with the “-force” operators:

                Get-Childitem “C:\Foo”-recurse -force

Now that the files are selected, which is tantamount to CTRL+A with display hidden files on, we are going to dump the results into the Set-ACL command with a pipe (|) operator:

                Get-Childitem “C:\Foo”-recurse -force | Set-ACL

Because we already defined the object we are applying the permissions to we can move right along to the-aclobject operator.  This operator says apply the following permissions to the previous object.  The following being the $acl that we defined earlier in the article:

                Get-Childitem “C:\Foo”-recurse-hidden | Set-ACL-aclobject $acl

And there you have it.  We have successfully applied your permissions to this folder full of goodies that you need to accomplish your mission.  As usual, should you have any suggestions, or even a better way to do it, let me know!  And please don’t forget to share, +1, like, and tweet this post to all of your Powershell using compatriots below!

No comments:

Post a Comment