Category Archives: Powershell

Give user access to remote file share via Powershell

In a hurry to write this post, so will add explanation later

Recently a fellow colleague asked me to help him in doing this in PowerShell, as usual I went to google, much to my disappointment I couldn’t find a single solution anywhere on web (TechNet, Script Center, Powershell,com etc.)
So, I decided to sit in the early morning and forge it out myself, by the time to go to office I had this working solution 🙂

Let me know if you guys need any help

$Computer = "sanil"
$user = "guest"
$domain = "BUILTIN"

cls
$s = Get-WmiObject -Class "Win32_LogicalShareSecuritySetting" -Filter "Name='Music'"
$sd = $s.GetSecurityDescriptor()

# List all users having access
$sd.Descriptor.DACL | ForEach-Object {$_.Trustee.Name}

$ACE = ([WMIClass] "\$Computerrootcimv2:Win32_ACE").CreateInstance()
$Trustee = ([WMIClass] "\$Computerrootcimv2:Win32_Trustee").CreateInstance()

$Trustee.Name = $user
$Trustee.Domain = $domain
$Trustee.SIDString =  (new-object security.principal.ntaccount $user).translate([security.principal.securityidentifier]) 

$ace.AccessMask = 2032127
$ace.AceFlags = 3
$ace.AceType = 0
$ace.Trustee = $Trustee

# New Secuity Descriptor
$nsd = ([WMIClass] "\$Computerrootcimv2:Win32_SecurityDescriptor").CreateInstance()

#Copy all except DACLs
$nsd.Properties["ControlFlags"].Value = $sd.Descriptor.Properties["ControlFlags"].Value
$nsd.Properties["Group"].Value = $sd.Descriptor.Properties["Group"].Value
$nsd.Properties["Owner"].Value = $sd.Descriptor.Properties["Owner"].Value
$nsd.Properties["SACL"].Value = $sd.Descriptor.Properties["SACL"].Value
$nsd.Properties["TIME_CREATED"].Value = $sd.Descriptor.Properties["TIME_CREATED"].Value

for($i=0; $i -lt $sd.Descriptor.DACL.Count; $i++)
{
    $nsd.DACL += $sd.Descriptor.DACL[$i]
}

$nsd.DACL += $ACE
# List all users having access
$nsd.DACL | ForEach-Object {$_.Trustee.Name}

$s.SetSecurityDescriptor($nsd) #Should return 0