PowerShell: Grant SMB Access

# grantSmbAccess.ps1

$computername='fileserver'
$shareName='TEST'
$account='domain\groupOrUsername'
$accessType='read' # also change or full

invoke-command -computername $computername -scriptblock{
    param($shareName,$account,$accessType)
    try{
        Grant-SmbShareAccess -Name $shareName -AccountName $account -AccessRight $accessType -force
        # Get-SmbShareAccess $shareName
        $object=(Get-SmbShare $shareName).Path
        # Translating SMB to NTFS equivalent: Full, Modify, ReadAndExecute
        $permission=switch($accessType.tolower()){
            'full' {'full'}
            'change' {'modify'}
            'read' {'ReadAndExecute'}
            Default {'ReadAndExecute'}
        }
        $acl=Get-Acl $object
        $grantAccess=New-Object System.Security.AccessControl.FileSystemAccessRule($account,$permission,'Allow')
        $acl.AddAccessRule($grantAccess)
        Set-Acl $object $acl
        return $true
    }catch{
        write-warning $_
        return $false
    }

} -Args $shareName,$account,$accessType

Leave a Reply

Your email address will not be published. Required fields are marked *