MattsBits
MattsBits

MattsBits

Using Windows Powershell To Create Network Shares  

by Matt Hawkins, 18/10/2010
Categories : Windows

Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language. PowerShell enables administrators to perform administrative tasks on both local and remote Windows systems.

For many people it is simply a replacement for the familiar Command Prompt and it is included with Windows 7.

The following information explains how you can list and create network shares using Powershell. I use the script to create shares on drives that are not mounted until after Windows has booted.

List all the shares on this computer :

Get-WmiObject Win32_Share


List all the shares on this computer sorted by type then name :
Get-WmiObject Win32_Share | sort type, name


List all the shares on another computer :
Get-WmiObject Win32_Share -computerName Name

where Name is the name of the computer!

Create a share :
$Shares = [wmiClass] 'Win32_share'
$Shares.create("E:My Data", "My Data", 0)

If the share is created successfully then it will return 0 otherwise it will return a non-zero number.

The following function can be included in a Powershell script :

Function CreateShare($Foldername,$Sharename) {
#
# This function creates a network share
#
# $Foldername - The full path to the share
# $Sharename  - The share name

  write-host "########## $Sharename ##########"

  # Check if the path exists
  IF (!(TEST-PATH $Foldername)) {
   # Create folder 
   NEW-ITEM $Foldername -type Directory
   write-host "Created $Foldername"
  }
 
  # Create Share but check to make sure it isnít already there
  If (!(GET-WMIOBJECT Win32_Share | Where-Object -FilterScript {$_.Name -eq $Sharename})) {
    # Create share
    $Shares = [wmiclass]"Win32_Share"
    $results = $Shares.Create($Foldername,$Sharename,0,0)
    if ($results.returnvalue=0) {
     # Share created ok
     write-host "Created $Sharename"
    } else {
     # Error creating share
     write-host "Failed to create $Sharename ERROR:" $results.returnvalue
    }
  } ELSE {
    # Share name already exists
    write-host "$Sharename already exists"  
  }

  write-host ""
}


You can then call the function as many times as you like at the end of the script :

CreateShare "E:My Data" "My Data"

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2017