Categories

Share Permissions – Removing

You’ve seen how to read share permissions and how to add share permissions – now its time to remove share permissions.  Most of the code we need is in the Add-Sharepermission function – it just needs a bit of a tweak.

#requires -Version 3.0
function Remove-SharePermission {
[CmdletBinding()]
param (
  [Parameter(Mandatory=$true)]
  [string]$sharename,

  [string]$domain = $env:COMPUTERNAME,

  [Parameter(Mandatory=$true)]
  [string]$trusteeName,

  [Parameter(Mandatory=$true)]
  [ValidateSet("Read", "Change", "FullControl")]
  [string]$permission = "Read",

  [string]$computername = $env:COMPUTERNAME
)

switch ($permission) {
   'Read'        {$accessmask = 1179817}
   'Change'      {$accessmask = 1245631}
   'FullControl' {$accessmask = 2032127}
}

 

$shss = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -Filter "Name='$sharename'" -ComputerName $computername
$sd = Invoke-WmiMethod -InputObject $shss -Name GetSecurityDescriptor |
select -ExpandProperty Descriptor

$sclass = [wmiclass]"\\$computername\root\cimv2:Win32_SecurityDescriptor"
$newsd = $sclass.CreateInstance()
$newsd.ControlFlags = $sd.ControlFlags

foreach ($oace in $sd.DACL){

if (($oace.Trustee.Name -eq $trusteeName) -AND ($oace.Trustee.Domain -eq $domain) -AND ($oace.Accessmask -eq $accessmask)) {
    continue
}
else
{
    $newsd.DACL += $oace
}
}

$share = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -Filter "Name='$sharename'"
$share.SetSecurityDescriptor($newsd)

} # end function

The function uses the same parameters as Add-Permission i.e. mandatory share name, trustee name and permission with optional computer and domain names. The switch statement converts the permission into an access mask.

Use Get-WmiObject to  get the current security descriptor and use [wmiclass] to create a new one.

Copy the control flags and the ACE except for the any that correspond to the trustee name, domain and the permission you want to remove.

Use SetSecurityDescriptor to apply the new permissions

Leave a Reply