Tuesday, December 11, 2012

Get Folder Permissions by Scripts (2)

I created a simple function in PowerShell script to get folder permissions. As I mentioned in my previous blog, a DOS command is used to get folder permissions: Calcs. If there is subfolder within a folder, the function provides recursive option to get subfolder permissions. In addition to that, the folder can contain wild characters such as "*data".

To get all the containers as a collection in PS, the command is Get-Item with option $_.PSIsContainer:

$fs = Get-Item -Path $p_Path | Where-Object {$_.PSIsContainer }

The following is the function

# Function: GetFolderPermission
# Created: [10/02/2012]
# Author: David Chu
# Arguments:
#   $p_Path: folder
#   $p_recursive:    true for recursive, false for not
# -------------------------------------------
# Purpose: get folder permissions
# -------------------------------------------
function GetFolderPermission(
 $p_Path,
 $p_outFile,
 $p_recursive)
{
 # get all the files matched and timestamp > comparing date
 $fs = Get-Item -Path $p_Path | Where-Object {$_.PSIsContainer }
 if ( $fs -ne $null )
 {
   foreach ($folder in $fs)
   {
     $fullDir = $folder.FullName
     Write-Output $fullDir
     $cmd =  'cacls "{0}"' -f $fullDir
     Invoke-Expression $cmd | out-File -Append $p_outFile
     if ( $p_recursive )

     {
       $fsSub = Get-ChildItem -Path $fullDir |Where-Object {$_.PSIsContainer}
       if ( $fsSub -ne $null)
       {
         foreach ($subDir in $fsSub)
         {
           $fullDir = $subDir.FullName
           GetFolderPermission $fullDir $p_recursive $p_outFile
         }
       }
     }
   }
 }
}

The above codes are very straightforward, therefore, no need to explain.

0 comments: