Create network shared folder with permissions using Powershell

Here it is:

$folderName = ‘c:/temp/shared’
$shareName = ‘NetworkShare’

if (!(Test-Path $folderName))
{
  New-Item $folderName -type Directory
}

if (!(Get-WmiObject Win32_Share -filter “name=’$shareName’”))
{
  $Shares=[WMICLASS]”WIN32_Share”
  $shares.create($folderName, $shareName, 0)
}

#Use shorter name for .Net class
$accessRule = [System.Security.AccessControl.FileSystemAccessRule]

$Acl = Get-Acl $folderName
$Acl.SetAccessRuleProtection($True, $False)
$rule = New-Object $accessRule(‘Administrators’,’FullControl’,’Allow’)
$Acl.AddAccessRule($rule)
$rule = New-Object $accessRule(‘your_domain\your_user’,’FullControl’,’Allow’)
$Acl.AddAccessRule($rule)

Set-Acl $folderName $Acl
(Get-WmiObject Win32_Share -filter “name=’$shareName’”) | Get-Acl | Format-List *

Replace your_domain and your_user with desired username.

Update: Had issues in Chef when trying to filter the shared folders by the one specified by $shareName variable, because the quotes were always removed by the Chef compiler. In this case, try the following:

$sharedDir = ((Get-WmiObject win32_share) | select Name).Name | where { !($_ -eq $null) -and $_.tolower().equals($shareName.ToLower()) }

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: