How to Use PowerShell to Create Shared Folders in Windows 7

How to Use PowerShell to Create Shared Folders in Windows 7

  • Comments 25
  • Likes

 

Summary: Guest blogger Sean Kearney shows you how to use Windows PowerShell to create shared folders and set permissions on a Windows desktop.

 

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I use Windows PowerShell to create shares?

-- SK

 

Hey, Scripting Guy! AnswerHello SK,

Microsoft Scripting Guy Ed Wilson here. Wrapping up Guest Blogger Week is Sean Kearney. Sean is a network administrator, a Microsoft Certified Technology Specialist in Windows Server Virtualization, Configuration, and a Microsoft Certified Systems Engineer and MVP in Windows PowerShell. He is a devoted and passionate computer enthusiast from the early 80s to the present day, having used just about every microcomputer ever. He is self-taught in computer programming with 65xx machine code, working with many technologies, but primarily Microsoft technologies. He deals with “anything thrown at him” from gnawed keyboards to recovery of Exchange servers to networking setups and isolating the realm of the unknown. His present position has him testing and deploying just about any new Microsoft technology he’s asked to as well as dealing with users in an enterprise class environment. Prior to this, he spent more than 8 years dealing with small business systems and home user environments. He absolutely loves Windows PowerShell, Windows 7, and Hyper-V and in that specific order. You will often find him hanging out online at http://www.powershell.ca.

Here’s Sean.

 

Creating networks shares is not a challenge.   Fire up the GUI, right-click Share, add the user or group, and set the permissions on the share. This is shown in the following image. It is not difficult, but it is also not seamless.

Image of creating network shares

So why not make it that way? We can certainly do this thanks to free tools such as Windows PowerShell and VBScript. But why Windows PowerShell? One word. Interactivity. We can test and put the pieces together one bit at a time.

Normally for a network share, we need something to share. A folder. So let’s make one:

NEW-ITEM C:\NetworkShare -type directory

And then we’re going to just…oh wait! What if the directory is already there? We should probably check for that first. In Windows PowerShell, there is a simple cmdlet called Test-Path that does exactly that. It tests to see if a particular file or directory is actually there.   It returns a Boolean $TRUE or $FALSE, depending on the results.

So if I’m going to make a new folder for the share, I can actually verify it’s there first. But of course I want to create the folder if it’s not there, so I plug in a “!” (NOT) into the decision

IF (!(TEST-PATH C:\NewShare)) {
               
NEW-ITEM C:\NewShare -type Directory
}

We now have folder and we have made sure to not mess up one that was already there. Now the tricky part: sharing. There is no cmdlet in Windows PowerShell for sharing, but there is the WIN32_Share class in WMI. To access it, all we need do is assign it to a variable for easy use:

$Shares=[WMICLASS]”WIN32_Share”

To create a share, we call up the Create method from Win32_Share. We can find out which methods are available on this particular object by using our good old friend, GET-MEMBER:

$Shares | GET-MEMBER

You’ll see right at the top a method called Create, which is used to create the shares. But Create has two rules:

  1. You must be an administrator on the machine.
  2. You must Run as administrator the Windows PowerShell console.

So creating a share requires three parameters: the name of the folder you are sharing, the name of the share, and the type of the share.  Don’t forget we could be sharing something other than a drive potentially.

Value

Meaning

0 (0x0)

Disk Drive

1 (0x1)

Print Queue

2 (0x2)

Device

3 (0x3)

IPC

2147483648 (0x80000000)

Disk Drive Admin

2147483649 (0x80000001)

Print Queue Admin

2147483650 (0x80000002)

Device Admin

2147483651 (0x80000003)

IPC Admin

So with a folder called C:\NetworkShare, if we try to share it as “Joey” we run the following command:

$Shares.Create(“C:\NetworkShare”,”Joey”,0)

Yeah! It’s done! Celebrate and…oh, right. We should have checked to see if it was there first. Right. Would have been a good idea. Well, that’s not a problem. That’s a feature of Windows PowerShell and WMI. Just use a GET-WMIOBJECT on Win32_share:

GET-WMIOBJECT Win32_Share -filter “name=’Joey’”

But like when we created the folder, we want this to happen only if it’s not there.  So we pull out that NOT (“!”) character:

If (!(GET-WMIOBJECT Win32_Share -filter “name=’Joey’”) {
               
$Shares.Create(“C:\NetworkShare”,”Joey”,0)
}

Now that we know which pieces work (because remember at this point we’re typing live commands into a shell), we can pull out our favorite editor and build that into a useful daily function

Function NEW-SHARE ($Foldername, $Sharename) {

               
# Test for existence of folder, if not there then create it
               
#
               
IF (!(TEST-PATH $Foldername)) {
                               
NEW-ITEM $Foldername -type Directory }

# Create Share but check to make sure it isn’t already there
#
If (!(GET-WMIOBJECT Win32_Share -filter “name=$Sharename”) {
               
$Shares.Create($Foldername,$Sharename,0)
}

}

There! Now we can have a field day with creating shares! One simple function in Windows PowerShell that will do all the work for us. Of course we could dramatically improve this function by working on some remoting, providing feedback to the administrator, permissions, and perhaps even have it playing a little song and show some pretty lights.

But, as Hammy the Hamster would say, that’s another story.

 

SK, that is all there is to using Windows PowerShell to create shares. Quick-Hits Friday is on deck tomorrow when we will talk about a variety of things. We ask you to follow us on Twitter and Facebook. If you have any questions, send email to us at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • you ignored the harder half of the question: share permissions.  

  • Can you provide a simple script to create a share on a Windows 2008 R2 Cluster and scope it specifically to one Client Access Point?

  • How to click on a GUI "Next Button" while installation

  • @Panda you could use sendkeys from the wshshell object, or you could try to use WASP from CodePlex.

    @Davis check the Scripting Guys Script Repository ... I know we have some cluseter scripts else check MSDN

    @Joe of course I did :-) I like to Use Icacls to do permissions, but I have an article coming up in which I am using WMI methods.

  • The New-Share function will work if you add

    $Shares=[WMICLASS]"WIN32_Share"

    before the $Shares.Create line

  • How do you perform the following on a remote computer?:

    $Shares=[WMICLASS]"WIN32_Share"

    I can tell it is different than gwmi win32_share -cn [remote]

  • I have a opposite scenario. Users in the network have shared the folders & I have to stop them. Any chance by which I can do it with single powershell script?

  • Looks like the guys left out a couple of ")"

    Try this:

    Function NEW-SHARE ($Foldername, $Sharename) {

                   # Test for existence of folder, if not there then create it

                   #

                   IF (!(TEST-PATH $Foldername)) {

                                   NEW-ITEM $Foldername -type Directory }

    # Create Share but check to make sure it isn’t already there

    #

    If (!(GET-WMIOBJECT Win32_Share -filter "name=$Sharename")) {

                   $Shares=[WMICLASS]"WIN32_Share"

                   $Shares.Create($Foldername,$Sharename,0)

    }

    }

  • @LernerML

    If you don't want certain directories shared, you could use this snippet:

    $badpaths = "C:\applications","C:\applications\someapp","C:\temp","C:\newshare"

    $servers = "Server1","Server2","Server3"

    foreach($server in $servers){

       $found = Get-WMIObject Win32_share -ComputerName $server

       foreach($share in $found){

           if($badpaths -contains $share.path){

               $Share.Delete()

               }

           }

       }

    You could also check for shared local printers with ($share.type -eq 1)

    It'd be really cool if you could see who created the share, and delete them based on creator, but I'm not that savvy. :(

  • thanks

  • you are missing a closing bracket when you create your New-Share Function

  • Ed are you saying that you can use Icacls to modify the permissions of the share as well as files?

  • Hi Ed - I am using the following script which does create the folder and share / security permissions but does NOT set the Share Name correctly. It is defaulting to FredFlintstone with no "$".

    Shouldn't the Share Name be able to be set the same as Win Server 2003?

    $NasPath = 'Z:\EDrives\FredFlintstone'

    $Shares=[WMICLASS]'WIN32_Share'

    $ShareName='FredFlintstone$'

    New-Item -type directory -Path $NasPath

    $Shares.Create($NasPath,$ShareName,0)

    $Acl = Get-Acl $NasPath

    $Ar = New-Object system.security.accesscontrol.filesystemaccessrule('Fred Flintstone','FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')

    $Acl.AddAccessRule($Ar)

    Set-Acl $NasPath $Acl

  • How do you modify/add the share permissions

  • @Share Name NOT being created correctly in Server 2008R2 - try adding a ` (escape character) in front of your $ in that path string.