O'Reilly logo

Monad (AKA PowerShell) by Andy Oakley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Manage Filesystem Permissions

Besides containing content layout and data, many filesystems also provide a layer of access control defined by a set of permissions granted to users on a per-file or per-folder basis. Although command-line modification of file permissions is possible with the cacls.exe tool, MSH also offers two cmdlets, get-acl and set-acl that give scripts access to these Access Control Lists (ACLs).

In this section, we'll look at two approaches to managing file permissions. In the first, we'll see the ease with which MSH can use existing command-line tools. In the second, we'll focus on the MSH-specific cmdlets.

How Do I Do That?

We've already seen how foreach can be used to loop through a number of items generated by a cmdlet, so let's start there:

    MSH D:\MshScripts> foreach ($file in get-childitem) {
    >>cacls.exe $file /E /G andy :F
    >>}
    >>
    processed file: C:\tmp\aclchange.msh
    processed file: C:\tmp\brownfox.txt
    processed file: C:\tmp\output.csv
    processed file: C:\tmp\start.msh

This isn't all that different from calling cacls.exe with a wildcard (*) parameter, so let's take it a step further. In this case, we'll recursively modify the permissions in a complete folder structure (still possible with the /T flag on cacls.exe), except for a few files (with the name "private.txt") that we'll leave untouched:

    MSH D:\MshScripts> foreach ($file in $(get-childitem -recurse)) {
    >>if ($file.FullName -notlike "*private.txt")
    >>{
    >>    cacls.exe $file.FullName /E /G Everyone:R > null ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required