|
function New-Share { |
|
param( |
|
[string] $ComputerName = $env:COMPUTERNAME, |
|
[string] $Path = 'C:\Temp', |
|
[string] $ShareName = 'Temp', |
|
[string] $AccountName = 'Domain Users', |
|
[ValidateSet('FullControl', 'Change','Read')] $AccessPermissions = 'Read', |
|
[string] $ShareDescription |
|
) |
|
|
|
# Convert the AccessPermissions |
|
$accessFlags = @{ |
|
FullControl = 2032127 |
|
Change = 1245631 |
|
Read = 1179817 |
|
}; $access = $accessFlags[$AccessPermissions] |
|
|
|
# Extract Domain and User account |
|
$Domain, $Identity = if($AccountName -match '\\') { |
|
$AccountName -split '\\' |
|
} else { |
|
$env:USERDOMAIN, $AccountName |
|
} |
|
|
|
# Build the Security Descriptor and Trustee objects |
|
$sd = ([wmiclass] "\\$ComputerName\root\cimv2:Win32_SecurityDescriptor").CreateInstance() |
|
$trustee = ([wmiclass] "\\$ComputerName\root\cimv2:Win32_Trustee").CreateInstance() |
|
$trustee.Name = $Identity |
|
$trustee.Domain = $Domain |
|
|
|
# Build the Access Control Entry object |
|
$ace = ([wmiclass] "\\$ComputerName\root\cimv2:Win32_ACE").CreateInstance() |
|
$ace.AccessMask = $access |
|
$ace.AceFlags = 3 |
|
$ace.AceType = 0 # 0 Allow, 1 = Deny |
|
$ace.Trustee = $trustee |
|
$sd.DACL = $ace.psObject.BaseObject |
|
|
|
# Create the share with the required permissions |
|
$mc = [wmiclass]"\\$ComputerName\root\cimv2:Win32_Share" |
|
$inParams = $mc.psbase.GetMethodParameters('Create') |
|
$inParams.Access = $sd |
|
$inParams.Description = $ShareDescription |
|
$inParams.MaximumAllowed = $null |
|
$inParams.Name = $ShareName |
|
$inParams.Password = $null |
|
$inParams.Path = $Path |
|
$inParams.Type = [uint32]0 |
|
$ret = $mc.psbase.InvokeMethod('Create',$inParams, $null) |
|
|
|
# Determine the return value from the WMI method |
|
Switch ($ret.ReturnValue){ |
|
0 { Write-Verbose 'Share created successfully'; break } |
|
2 { Write-Error 'Access denied (2)'; break } |
|
8 { Write-Error 'Unknown failure (8)'; break } |
|
9 { Write-Error 'Invalid name (9)'; break } |
|
10 { Write-Error 'Invalid level (10)'; break } |
|
21 { Write-Error 'Invalid parameter (21)'; break } |
|
22 { Write-Error 'Duplicate share (22)'; break } |
|
23 { Write-Error 'Redirected path (23)'; break } |
|
24 { Write-Error 'Unknown device or directory (24)'; break } |
|
25 { Write-Error 'Net name not found (25)'; break } |
|
default { Write-Error 'Other Error (26–4294967295)' } |
|
} |
|
} |