[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


How Can I Export Share Permissions for each Server, from Server.txt Input File?

Posted on 2014-03-18
Medium Priority
Last Modified: 2014-03-19
Firstly, I already have the NTFS permissions. I ONLY need the "Share" permissions.

I have been working to understand and manipulate this script from here [http://poshcode.org/3398] to export all share permissions to an HTML file, per server. I understand that this script is not written to access an input file, so I have been implementing variations of the code to include these few lines as described here [https://www.sapien.com/forums/viewtopic.php?f=18&t=6607], to force the Main Script to query the "servers.txt" file and loop through the whole script, then iterate for every servername in the servers.txt file. I will greatly appreciate help to understand exactly how to run this script against many servers. I tried to place this in my PS $Profile, then tried to use it as a ".ps1" file. I will be glad to concatenate in Excel if I need to work with a one-liner per server.

Also, of note is that when I initially ran this a few hours ago, it ran with no errors, then I noticed that the HTML file was created after I refreshed my $Profile by typing .$Profile at cmd prompt or by closing and restarting PS. But subsequently I noticed this line, which is coded in the script:

ERROR: cannot enumerate share permissions

It continued to output an HTML file (only for the local server) but only AFTER I refreshed my "$Profile".

Thank you!

Get-Content servers.txt |
         # call script file and pass variable $_ which is current line of file
         c:\folder\filename.ps1 -server $_

Function Get-SharePermissions($ShareName){
    $Share = Get-WmiObject win32_LogicalShareSecuritySetting -Filter "name='$ShareName'"
        $obj = @()
        $ACLS = $Share.GetSecurityDescriptor().Descriptor.DACL
        foreach($ACL in $ACLS){
            $User = $ACL.Trustee.Name
            if(!($user)){$user = $ACL.Trustee.SID}
            $Domain = $ACL.Trustee.Domain
                2032127 {$Perm = "Full Control"}
                1245631 {$Perm = "Change"}
                1179817 {$Perm = "Read"}
            $obj = $obj + "$Domain\$user  $Perm<br>"
    if(!($Share)){$obj = " ERROR: cannot enumerate share permissions. "}
    Return $obj
} # End Get-SharePermissions Function

Function Get-NTFSOwner($Path){
    $ACL = Get-Acl -Path $Path
    $a = $ACL.Owner.ToString()
    Return $a
} # End Get-NTFSOwner Function

Function Get-NTFSPerms($Path){
    $ACL = Get-Acl -Path $Path
    $obj = @()
    foreach($a in $ACL.Access){
        $aA = $a.FileSystemRights
        $aB = $a.AccessControlType
        $aC = $a.IdentityReference
        $aD = $a.IsInherited
        $aE = $a.InheritanceFlags
        $aF = $a.PropagationFlags
        $obj = $obj + "$aC | $aB | $aA | $aD | $aE | $aF <br>"
    Return $obj
} # End Get-NTFSPerms Function

Function Get-AllShares{
    $a = Get-WmiObject win32_share -Filter "type=0"
    Return $a
} # End Get-AllShares Function

# Create Webpage Header
$z = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`"  `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$z = $z + "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$z = "<head><style>"
$z = $z + "TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}"
$z = $z + "TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}"
$z = $z + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}"
$z = $z + "</style></head><body>"
$z = $z + "<H4>File Share Report for $env:COMPUTERNAME</H4>"
$z = $z + "<table><colgroup><col/><col/><col/><col/><col/><col/></colgroup>"
$z = $z + "<tr><th>ShareName</th><th>Location</th><th>NTFSPermissions<br>IdentityReference|AccessControlType|FileSystemRights|IsInherited|InheritanceFlags|PropagationFlags</th><th>NTFSOwner</th><th>SharePermissions</th><th>ShareDescription</th></tr>"

$MainShares = Get-AllShares
Foreach($MainShare in $MainShares){
    $MainShareName = $MainShare.Name
    $MainLocation = $MainShare.Path
    $MainNTFSPermissions = Get-NTFSPerms -Path $MainLocation
    $MainNTFSOwner = Get-NTFSOwner -Path $MainLocation
    $MainSharePermissions = Get-SharePermissions -ShareName $MainShareName
    $MainShareDescription = $MainShare.Description

    $z = $z + "<tr><td>$MainShareName</td><td>$MainLocation</td><td>$MainNTFSPermissions</td><td>$MainNTFSOwner</td><td>$MainSharePermissions</td><td>$MainShareDescription</td></tr>"
$z = $z + "</table></body></html>"
$OutFileName = $env:COMPUTERNAME + "ShareReport.html"
Out-File -FilePath .\$OutFileName -InputObject $z -Encoding ASCII
$OutFileItem = Get-Item -Path .\$OutFileName
Write-Host " Report available here: $OutFileItem" -Foregroundcolor Yellow
Question by:kontrariankid
  • 3
  • 3

Author Comment

ID: 39939585
I need help with this.. I will increase points if necessary, but I am not seeing the option to do so at this moment in the comments section as indicated here:

LVL 41

Expert Comment

ID: 39939975
500 points is the maximum.
I'm not quite clear, do you need a separate file for each server?

Author Comment

ID: 39940214
Yes sir, I would like to create one HTML report for each server, which lists all shares on said server. But maybe it makes more sense to create one HTML file that contains permissions for ALL servers in the servers.txt input file, as long as there is a separation header that indicates where one server stops and the next one starts.

The above script did output one HTML file named "SAL9001ShareReport.html", but only after I reloaded my PS profile, and now every time I close and restart PS, the same file is created...

$OutFileName = $env:COMPUTERNAME + "ShareReport.html"

I am attaching a copy of that output HTML file here.
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

LVL 41

Accepted Solution

footech earned 2000 total points
ID: 39940473
Try saving the below as a .ps1 file.  Then run it.  It will query a file "serverlist.txt" for the list of servers.
$typehash = @{
    0 = "Allow"
    1 = "Deny"

$permhash = @{
    1179817 = "Read"
    1245631 = "Change"
    2032127 = "Full Control"

# Create Webpage Header
$head = @"
TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}
TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}

$body = @"
<H4>File Share Report for $server</H4>

$servers = Get-Content serverlist.txt

@(foreach ($server in $servers)
    $shareInfo = @(Get-WmiObject Win32_Share -ComputerName $server -filter "type = 0" | Select Name,Path)
    @(foreach ($share in $shareInfo)
        $shareACL = (Get-WmiObject Win32_LogicalShareSecuritySetting -ComputerName $server -filter "name = '$($share.name)'").GetSecurityDescriptor().Descriptor.DACL
        $shareACL | ForEach `
            $user = If ($_.Trustee.Domain)
                    { $_.Trustee.Domain, $_.Trustee.Name -join "\" }
                    { $_.Trustee.Name }
            $type = switch ($_.AceType)
                        0 { $typehash[0]; break }
                        1 { $typehash[1]; break}
            $perm = switch ($_.AccessMask)
                        1179817 { $permhash[1179817]; break }
                        1245631 { $permhash[1245631]; break }
                        2032127 { $permhash[2032127]; break }
            New-Object PsObject -Property @{
                    Server = $server
                    ShareName = $share.name
                    Path = $share.path
                    UserOrGroup = $user
                    Type = $type
                    Permission = $perm
    }) | Sort Server,ShareName,UserOrGroup |
     Select ShareName,Path,UserOrGroup,Type,Permission |
     ConvertTo-Html -Head $head -Body $body | Out-File shareinfo-$server.html -Encoding ascii

Open in new window

Edit:  BTW, thought I should mention that the above is a modification of code I posted in http:Q_28289529.html, which in turn was partially based on the link you provided.

Author Comment

ID: 39941434
footech.. thank you very much for your help with this! i am attaching a copy of one of the HTML files for your fans.

it works wonderfully! i love the clean appearance of your code as well.

it throws this message, but this is obviously related to many servers being unreachable for whatever reason.

do you think it will be feasible for me to wrestle with this to integrate the NTFS permissions as well with an additional column? i like the Get-ACL approach, but how much work do you think it would be to reach that goal?

can you tell me what "GetWMICOMException" is related to in this instance?

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At \\\foldername\subfolder\PS1\EE_SharePerms\subfolder\EE_Get-SharePerms.ps1:29 char:33
+     $shareInfo = @(Get-WmiObject <<<<  Win32_Share -ComputerName $server -filter "type = 0" | Select Name,Path)
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
LVL 41

Expert Comment

ID: 39941494
"The RPC server is unavailable" error can be caused by a few reasons, including: 1) incorrect DNS info, 2) firewall blocking ports, 3) service not running, 4) maybe others.

The code really doesn't have any error handling.  About the most basic you could do is including the following inside the foreach loop, which would just test if the machine is pingable before trying to get share info.
If ( Test-Connection $server -count 1 -quiet )
  #do stuff

Open in new window

I see no reason why you couldn't add NTFS permissions, but it's not without its challenges.  One question that you would have to decide on is how would the data (the HTML tables) be formatted.  You might notice that the output of what I provided is a bit different than the output of the script in the link you provided.  From your first sample you can see that it groups all share permissions into one cell (and all NTFS perms into another), whereas mine creates a separate row for each share permission - this is more useful when exporting to a .CSV.  If you did the same thing for NTFS perms that could get pretty long.  It's going to depend on what will be useful for you.  Also, if I was going to rework the script to include NTFS perms, I would probably opt to also use PowerShell Remoting to make things easier and quicker.  So, overall it's not a trivial addition.

Featured Post

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Suggested Courses
Course of the Month19 days, 8 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question