Managing Windows file shares with PowerShell

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.

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 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.

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.

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.

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.

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.

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.

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 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.

Removing the Logs file share with Remove SmbShare

Removing the Logs file share with Remove SmbShare

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the forum!

2+
Share
10 Comments
  1. 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

    0

  2. @techieweenie

    Backuping a PowerShell configuration is much easier with XML.

    To backup your permissions:

    To restore your permissions:

    5+

  3. Ankit S 1 year 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.")

    }

    }

     

    0

    • @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.

       

      1+

  4. 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"
     

    1+

  5. John Strode 12 months 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

     

    0

  6. Manik 12 months ago

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

    0

  7. Hardeep 8 months 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
                    }

    0

  8. Joseph Sgueglia 2 months 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.

    0

    • 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.

      0

Leave a reply

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

*

© 4sysops 2006 - 2020

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