You could manage file shares through PowerShell, but before PowerShell 3, it was not the most intuitive process. PowerShell 3 on Windows 8/Windows Server 2012 and higher introduced the SmbShare module. This module contains several commands that make managing file shares in Windows less of a headache.
Avatar

Creating and managing file shares through the GUI in Windows is something most administrators should be familiar with. It's a pretty straightforward process. However, things can get out of hand pretty fast when you need to manage multiple shares across multiple computers. With PowerShell, you can easily automate the task.

SmbShare commands available in PowerShell

SmbShare commands available in PowerShell


Listing current file shares

Let's get started by listing the currently configured shares with Get-SmbShare.

List of shares on the current machine

List of shares on the current machine

I haven't created any file shares on this computer yet, so the command returns a list of the default shares Windows created by default. This will also return any configured hidden shares.

To target a specific share, we can use the -Name parameter to specify the name of the share we want to return and then pipe it to Select to view all the properties for that share.

Get-SmbShare -Name C$ | select *
Get all the properties for the C$ share

Get all the properties for the C$ share

Creating a new file share

Now let's go ahead and create a new file share. Here are the details I'm going to use for my new share:

Name: Logs
Path: C:\Shares\Logs
Description: Log Files

You'll need to make sure the folder path exists prior to running this command.

New-SmbShare -Name Logs -Description "Log Files" -Path C:\Shares\Logs
Create a new share for log files

Create a new share for log files

Modifying share properties

Using the Set-SmbShare command, we can modify the properties of an existing share. Let's go ahead and modify the description property to specify the type of log files in this folder.

Set-SmbShare -Name Logs -Description "Application Log Files" -Force
Modifying share properties with Set SmbShare

Modifying share properties with Set SmbShare

If you tab complete through the parameters of Set-SmbShare, you can see the other share properties you can modify with this command.

Granting file share permissions

After creating the share, we can view the permissions associated with it by running Get-SmbShareAccess.

Getting the share permissions of the Logs share

Getting the share permissions of the Logs share

As you can see, creating the share gave the Everyone group Read access to the share. We should probably go ahead and change that to lock down the permissions so that only the users who need access to this share will have permissions.

To do this, we can use Grant-SmbShareAccess to specify the users or groups we wish to have access to the share as well as what level of access they will have. Let's start with adding an Active Directory group I have created for users who will have Read access to the Logs share called corp\LogViewers. Note that you can use tab completion on the -AccessRight parameter. The possible values for this parameter are Change, Custom, Full, and Read. For this, I'm going to select Read.

Grant-SmbShareAccess -Name Logs -AccountName corp\LogViewers -AccessRight Read
Granting Read permissions to the Logs share

Granting Read permissions to the Logs share

If you omit the -Force parameter, it will prompt you to confirm this action. If you would like to suppress this prompt, simply include the -Force parameter.

Now that the corp\LogViewers group has Read access, I want to add another group called corp\LogAdmins, which is going to have Change rights to the share.

Grant-SmbShareAccess -Name Logs -AccountName corp\LogAdmins -AccessRight Change -Force
Granting Read permissions to the Logs share

Granting Read permissions to the Logs share

Removing file share permissions

Now that the correct groups have permissions to the file share, let's remove the Everyone group. For removing a permission for a file share, we are going to use the Revoke-SmbShareAccess command. This will remove the permissions for the group we specify with the ­-AccountName parameter.

Revoke-SmbShareAccess -Name Logs -AccountName Everyone -Force
Removing the Everyone group from the file share permissions

Removing the Everyone group from the file share permissions

Denying permissions to a file share

You may need to deny specific users or groups from having access to a file share for security reasons. Any Deny permissions will supersede any Allow permissions. So even if users possess Read or Change permissions to the share, if you specifically deny them permission to that share, or if they are in a denied group, they will not be able to access that share.

To deny access for a user or group to the file share, we are going to use the Block-SmbShareAccess command. In this case, I am going to deny the group corp\AppUsers.

Block-SmbShareAccess -Name Logs -AccountName corp\AppUsers -Force
Denying access to the Logs file share

Denying access to the Logs file share

The output shows the addition of the corp\AppUsers group with an AccessControlType of Deny.

Running UnBlock-SMBShareAccess will remove the Deny permission for the user or group specified.

UnBlock-SmbShareAccess -Name Logs -AccountName corp\AppUsers -Force
Unblock a user or group's access on a file share

Unblock a user or group's access on a file share

Removing a file share

If you no longer have a need for a particular file share, we can use the Remove-SmbShare command. This will turn off sharing for that particular folder but will not delete the folder or any of its contents.

Subscribe to 4sysops newsletter!

Remove-SmbShare -Name Logs -Force
Removing the Logs file share with Remove SmbShare

Removing the Logs file share with Remove SmbShare

avatar
16 Comments
  1. Avatar
    Kim Vogel (Rank 2) 5 years ago

    Hi Matt, this is very helpful. What if I wanted to do this:

    Get-SmbShare | Get-SmbShareAccess | Export-Csv “\temp.csv” -NoTypeInformation
    And then, if the shares get corrupted or we want to restore the permissions, how do we use the .csv to do that? I just need to know how to set up the variables so that we can run a restore script and put everything back as before.

    Thanks,

    Kim

  2. Avatar

    @techieweenie

    Backuping a PowerShell configuration is much easier with XML.

    To backup your permissions:

    Get-SmbShare | Get-SmbShareAccess | Export-Clixml -Path C:\Temp\SmbPermissions.xml

    To restore your permissions:

    #Removing default or current permissions
    Get-SmbShare | Get-SmbShareAccess | ForEach-Object -Process {Revoke-SmbShareAccess -Name $PSItem.name -AccountName $PSItem.accountname}
    
    #Assigning backuped permissions
    $PermissionList = Import-Clixml -Path C:\Temp\SmbPermissions.xml
    foreach($Permission in $PermissionList){
        Grant-SmbShareAccess -Name $Permission.Name -AccountName $Permission.AccountName -AccessRight $PermissionList.AccessRight
    }
    avatar
  3. Avatar
    Ankit S 5 years ago

    Hello All,

     

    I have a requirement where my IS Security Team wants us to remove Everyone Group from the shared folders and add Äuthenticated Users group instead. Our Enviorment is mix of Windows 8 /10 on clients and Windows 2k8/2k12/2k16 on server side.

    Now the point here is that i dont have the list of the folders on which we need to carry out following change, so i would need help in powershell script which can be set as startup script to help me achive this..

    I got the script below from one of the forums but it doesnt work for me on Win10 Desktop. This script does list the folder which has Everyone added in share permission, But doesnt remediate the permissions.

     

    It would be great if someone can please help me acheive this..

     

    Regards

    AS

    ####################################################################

    ## ##

    ## This script will remove the "Everyone" group from any shares ##

    ## on the server not included in the exclude list. ##

    ## ##

    ####################################################################

     

    ## List of drives that should not be checked for share permissions

    $excludeList = 'D$','C$','ADMIN$','F$','IPC$','print$'

     

     

    Get-WmiObject -Class Win32_LogicalShareSecuritySetting | foreach {

    $name = $_.name

     

    if ($excludeList -notcontains $name){

    $newDescriptor = $_.GetSecurityDescriptor().descriptor

    $newDescriptor.dacl = $_.GetSecurityDescriptor().Descriptor.Dacl | Where {$_.trustee.name -ne 'Everyone'}

    $_.SetSecurityDescriptor($newDescriptor)

    Write-host ($name + " has been validated/remediated.")

    } else {

    Write-host ($name + " has been excluded.")

    }

    }

     

    • Avatar

      @Ankit

      Here is my proposition.

      You must adapt line 45 with values from line 33 to 35.

      If you have more questions, please open a topic in the PowerShell forum.

      $ComputerList = @(
          'Computer1'
          'Computer2'
      )
      
      $ExclusionList = 'ADMIN\$','IPC\$' -join '|'
      
      $ScriptBlock = {
      
          $ShareList = Get-CimInstance -ClassName Win32_Share |
                  Where-Object -FilterScript {
                      #keeps only object from the FileSystem
                      $PSItem.Path -notmatch '^\w:\\$' -and
                      #excludes administrative shares like C$
                      $PSItem.Path -match '^\w:\\\.*' -and
                      #excludes a custom list
                      $PSItem.Name -notmatch $using:ExclusionList
                  }
          
          foreach ($Share in $ShareList) {
              
              $Filter = "name='{0}'" -f $Share.Name
              $SecuritySettings = Get-WmiObject -Class Win32_LogicalShareSecuritySetting -Filter $Filter
              $Descriptor = $SecuritySettings.GetSecurityDescriptor().descriptor
              $CurrentDacl = $Descriptor.dacl       
      
              [System.Management.ManagementBaseObject[]]$NewDacl = $CurrentDacl.Where({$_.Trustee.Name -ne 'Everyone'})
      
              $ComputerName = $env:COMPUTERNAME
      
              #AccessPermissions
              $accessFlags = @{
                  FullControl = 2032127
                  Change = 1245631
                  Read = 1179817
              }
              
              #Build the Trustee objects
              $Trustee = ([wmiclass] "\\$ComputerName\root\cimv2:Win32_Trustee").CreateInstance()
              $Trustee.Name = 'Authenticated Users'
              $Trustee.Domain = ''
              
              # Build the Access Control Entry object
              $Ace = ([wmiclass] "\\$ComputerName\root\cimv2:Win32_ACE").CreateInstance()
              $Ace.AccessMask = $accessFlags['Read']
              $Ace.AceFlags = 3 # ContainerInherit + ObjectInherit
              $Ace.AceType = 0 # 0 Allow, 1 = Deny
              $Ace.Trustee = $Trustee
              
              [array]::Resize([ref]$NewDacl, $NewDacl.Count + 1)
              $NewDacl[$NewDacl.Count-1] = $Ace
              
              $Descriptor.dacl = $NewDacl
              $SecuritySettings.SetSecurityDescriptor($Descriptor)
          }
      }
      
      Invoke-Command -ComputerName $ComputerList -ScriptBlock $ScriptBlock

       

  4. Avatar

    Can the value of the Parameters in New-SMBShare be represented by Variables?

    You seem to infer this when you answered Kim Vogel's question above.

    New-SmbShare -Name $SHARE -PATH $PATH -Description "Test Shared Folder" -ReadAccess $SHARERead -ChangeAccess $SHAREModify -FullAccess $SHAREFullControl

    When I run the script no errors are generated but no additional entries are added to the default Share permissions of everyone.
    If I explicitly put in the values then these values are added to the share permissions.

    New-SmbShare -Name $SHARE -PATH $PATH -DescriPtion “Test Shared Folder” -ReadAccess “Everyone”,”NashUSWF-DEV-ANNEX-MASNAC” -ChangeAccess “Authenticated Users” -FullAccess “administrators”
     

  5. Avatar
    John Strode 4 years ago

    Can multiple accounts be added to a share using PowerShell? 

    I'm trying to setup remote shares on a server by first creating the default share with New-SmbShare and then adding groups to the share using Grant-SmbShareAccess.

    The code works for a single group but balks at adding more than one group.

    $Read = 'Nash\UTLPLN-NAS-PROD-RO', 'Nash\USWF-DEV-ANNEX-MASNAC'

      ##Create a default share with default permissions 
        $SHARE
        $PATH
        write-host "Creating SHARE: $SHARE" -ForegroundColor green
        Start-Sleep 15

        New-SmbShare -ErrorAction Stop -Name $SHARE -PATH $Path -Description 
        'Test Shared Folder' -CimSession $Session

       ##Add account with read share permission to the Share
        $SHARE
        $READ
        write-host "Adding $READ to the Read Share Access for the share: 
        $SHARE" -ForegroundColor green
        Start-Sleep 15

        Grant-SmbShareAccess -Name $share -AccountName $Read -AccessRight 
        Read -Force -CimSession $Session

    Error using the $READ above

    'Nash\UTLPLN-NAS-PROD-RO', 'Nash\USWF-DEV-ANNEX-MASNAC'
    Adding 'Nash\UTLPLN-NAS-PROD-RO', 'Nash\USWF-DEV-ANNEX-MASNAC' to the Read Share Access for the share: C_APPSTest1
    Grant-SmbShareAccess : No mapping between account names and security IDs was done. 
    At C:\Users\$jstrode\Documents\PowerShell_Scripts\Create-SMBShare(CimSession).ps1:79 char:9
    +         Grant-SmbShareAccess -Name $share -AccountName $Read -AccessR …
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (MSFT_SmbShare (…copeName = "*"):ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [Grant-SmbSh 
       areAccess], CimException
        + FullyQualifiedErrorId : Windows System Error 1332,Grant-SmbShareAccess
        + PSComputerName        : ABC12345.Nash.COM

     

  6. Avatar
    Manik 4 years ago

    How to provide the access of remote server share folder..? and Need to validate the owner name

  7. Avatar
    Hardeep 4 years ago

    I want to create  a bulk folders from a list of  folders from a text/csv file and than create a hidden share

    for example if the share name is  Acc-NYK-Finance, we have two security groups  Acc-NYK-Finance-Modify  and Acc-NYK-Finance-Read,  after creating the shares, i want to add them to the share level  and assign the modify with  modify permission and  Read only with Read permission,  sometimes i only have  Modify group,

    also i dont want to disable inheritance and  assign in security  local administrators,  full permission, system, full permission, and   domian users,  modify permission

     

    i dont want to use the path to create the shares, as they might be existing shares in the  folder and i dont want to screw them up

     

    $filefolder="c:\temp\folders.txt"
    $Dir = "C:\DEST"

    #Create the folders
    Get-Content "$filefolder" |
        ForEach-Object {
            $dirPath = Join-Path "$Dir" $_
            New-Item $dirPath -ItemType Directory
        }

        $file = Import-CSV "$filefolder"
    foreach ($line in $file)
                    {
                    $share = "$"+$line.folder                
                    $path = “C:\Temp\users\$($line.folder)”
                    New-SMBShare -Name $share$ -Path $path
                    }

  8. Avatar
    Joseph Sgueglia 3 years ago

    Hi all,

     

    We're trying to remove ALL users on the share level permissions and add the "Everyone" group with full control, for all shares on the file server. Does anyone have a powershell script to do this? Would GREATLY appreciate any help! Been searching everywhere.

    • Avatar
      Leos Marek (Rank 4) 3 years ago

      Its a very easy script, I will check later when I have time.

      But – you should never add Everyone to a share like that. Its against security best practice. You should use Authenticated Users group instead.

  9. Avatar
    Razi 3 years ago

    Hi does anyone have a ps script to list the file share and ntfs permission together script to get shared folder and NTFS permission from list of servers

    • Avatar Author
      Matt McElreath 3 years ago

      Here's a quick example of how you could do this. You may need to modify it to fit your needs though:

      $share = Get-SmbShare -Name <sharename>

      $acl = Get-Acl -Path $share.Path

      $share | Get-SmbShareAccess
      $acl.Access

  10. Avatar
    Razi 3 years ago

    Thanks, I am looking for something without using smbshare.I want to list the file share and ntfs permission together in a csv file column wise. Appreciate your help.

  11. Avatar
    Razi 3 years ago

    I mean can we use Get-WmiObject or any other command let to achieve the same (to list the file share and ntfs permission)

Leave a reply

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

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account