Assigning File Share permissions using Power Shell

Recently I was working on some Power Shell scripts for configuring my Windows Server 2012 machines. One of the task was to create a File share on a remote server and then share it and then assign NTFS and Share permissions.

Assigning NTFS permissions was simple however for assigning share permissions, I have to search a lot and luckily I found that in Windows 2012, a cmdlet is being added for this purpose and below is how I achieved this.

Obviously i took the names of remote server and share name as input in variables as $QServer and $QShare

# Make the folder

$FullPath= "\\"+$QServer+"\c$\"+$QShare
mkdir $FullPath
$Path="c:\"+$QShare

# Create the File Share

(get-wmiobject -list -ComputerName $QServer |Where-Object -FilterScript {$_.Name -eq "Win32_Share"}).InvokeMethod("Create",($Path,$QShare,0,100,"My Directory"))

# Assign the NTFS Permissions to Administrators

$AccessRule =New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl","ContainerInherit,ObjectInherit","None","Allow")
$ACL=get-acl \\$QServer\$QShare
$ACL.SetAccessRule($AccessRule)
set-acl \\$QServer\$QShare -AclObject $acl

# Remove “Everyone” from Share permissions and assign the Share Permissions to “Administrators”

Revoke-SmbShareAccess -name $QShare -CimSession $QServer -AccountName Everyone -Force
Grant-SmbShareAccess -name $QShare -CimSession $QServer -AccountName Administrators -AccessRight Full –Force

I hope this will be helpful for people working on similar tasks.

Cheers !!