Replace security on existing share with WMI in PowerShell (update post)
This is an update of the script from my old Blog /\/\o\/\/ PowerShelled: Replace Security on existing share using MSH to PowerShell V2, I came at this post while recourcing a question about translating a SID, that I tested a lot with on my old blog see also the other posts about this here where you can find more examples.
As I was at it I rewrote the existing script to work in PowerShell V2
Changes,
- Changed MshObject to PsObject (name change after Beta)
- Added CreateInstance() to create the Abstract WMI Classes (seems that that was not needed before WMI wrapper was added in RC1)
- By testing I found out that the script also did work with SID in string form now, before I could not get it working
Of course this script is also a candidate for further refactoring to an advanced function ( for example to check the value for mode if it is valid), but thats might be for a followup post.
# Set-SharePermission function
# Sets the security of a existing Share
# /\/\o\/\/ 2005-2010
Function set-Sharepermissions {
PARAM (
$share = "Test"
$user = "administrators"
$Domain = $null
$mode = "Change"
)
$sd = (new-object management.managementclass Win32_SecurityDescriptor).CreateInstance()
$ace = (new-object management.managementclass Win32_ace).CreateInstance()
$Trustee = (new-object management.managementclass win32_trustee).CreateInstance()
$Account = new-object system.security.principal.NtAccount($user)
$SID = $Account.translate([system.security.principal.securityidentifier])
#[byte[]]$ba = ,0 * $sid.BinaryLength
#$sid.GetBinaryForm($ba,0)
$Trustee.Domain = $Domain
$Trustee.Name = $user
#$Trustee.SID = $ba
$Trustee.SIDString = $sid.Value
switch ($mode) {
"Full" {$ace.AccessMask = 2032127}
"Change" {$ace.AccessMask = 1245631}
"Read" {$ace.AccessMask = 1179817}
}
$ace.AceType = 0
$ace.AceFlags = 3
$ace.trustee = $trustee
$SD.DACL = @($ACE.psobject.baseObject)
$share = get-wmiObject win32_share -filter "name='$share'"
$inparams = $share.GetMethodParameters("setShareInfo")
$inParams["Access"] = $SD.psobject.baseObject
$share.invokemethod("setshareInfo",$inparams,$null)
}
On my old blog you can also find another post : /\/\o\/\/ PowerShelled: PowerShell Import Shares and Security info ... to complely export and import a complete share complete with security.
With the example in this post you should also be able to get that sample working again.
Enjoy,
Greetings /\/\o\/\/