-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetShares.ps1
More file actions
608 lines (521 loc) · 18.7 KB
/
getShares.ps1
File metadata and controls
608 lines (521 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# ShareManager.ps1
# RetiredScriptingGuy
# Modified 6/28/2012
function Get-Shares
{
<#
.SYNOPSIS
Use this script to export and import the security settings of each share
.DESCRIPTION
This script will export or import existing Shares complete with security Info
.PARAMETER ParameterA
The server name
.PARAMETER ParameterB
File name for export or import
.PARAMETER ParameterC
Export or Import
.EXAMPLE
PS C:\> Get-Shares Servername c:\temp\shares.csv Export
.INPUTS
System.String,System.Int32
.OUTPUTS
System.String
.NOTES
Must be a Domain Administrator to run.
.LINK
about_functions_advanced
.LINK
about_comment_based_help
#>
[CmdletBinding()]
[OutputType([System.Int32])]
param(
[Parameter(Position=0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Server,
[Parameter(Position=1, Mandatory = $true)]
[ValidateNotNull()]
[System.String]
$file,
[Parameter(Position=2)]
[ValidateNotNull()]
[System.String]
$mode
)
try
{
if(($mode -match "Export") -or ($mode -match "export"))
{
$filename = $file
# get Shares (Type o is "Normal" shares)
$shares = gwmi Win32_Share -ComputerName $Server -filter 'type=0'
# combine Shares with Security info
$ShareInfo = @()
foreach ($share in $shares) {
$ShareSec = gwmi Win32_LogicalShareSecuritySetting `
-filter "name='$($share.name)'"
if($ShareSec)
{
$sd = $ShareSec.InvokeMethod('GetSecurityDescriptor',$null,$null)
$sd
$ShareInfo += $sd.Descriptor.DACL |`
% { $_ | select @{e={$share.name};n='Name'},
@{e={$share.Path};n='Path'},
@{e={$share.Description};n='Description'},
AccessMask,
AceFlags,
AceType,
@{e={$_.trustee.Name};n='User'},
@{e={$_.trustee.Domain};n='Domain'},
@{e={$_.trustee.SIDString};n='SID'}
}
}
Else
{
$ShareInfo += $share | select Name,Path,Description
$share
}
}
# Export them to CSV
$ShareInfo | select Name,Path,Description,User,Domain,SID,
AccessMask,AceFlags,AceType | export-csv -noType $filename
if(Test-Path ($filename))
{
Write-Host "Export Successful"
}
}
#end of if(($mode -match "Export") -or ($mode -match "export"))
if(($mode -match "Import") -or ($mode -match "import"))
{
[String]$FileServer = $Server
#Import the CSV file
write-host "Importing the CSV Info"
$ShareList = Import-Csv -Path $file
write-host " Complete" -ForegroundColor green
write-host "Sorting share list"
#Sort the Shares
$ShareList = $ShareList | sort-object {$_.name}
write-host " Complete" -ForegroundColor green
Function Check-CleanInput
{
[CmdletBinding()]
param($arrCSVShareInfo)
$blnCleanInput = $null
$blnCleanInput = $true
# used below to check domain, user
$strThisDomainName = gc env:UserDomain
$arrCSVShareInfo | % {
#Domain
#If ($blnCleanInput -eq $true)
#{
#If ((($_.domain -match $strThisDomainName) -ne $true)`
#-and (($_.domain -match "builtin") -ne $true))
# {
#
#Trap {Continue;}
#Throw "The domain name in the CSV file makes the script uncomfortable"
#$blnCleanInput = $false
#}
#}
#Checks for username and group names
# If ($blnCleanInput -eq $true)
# {
# If ($_.Domain -eq $strThisDomainName)
# {
# $blnDoesUserExist = Check-DoesUserExist ($_.User)
# If ($blnDoesUserExist -eq $false)
# {
# #If the user in the CSV isn't a user, check if its a group.
# $blnDoesGroupExist = Check-DoesGroupExist($_.User)
# If ($blnDoesGroupExist -eq $false)
# {
# Trap {Continue;}
# Throw "The user in the CSV doesn't exist"
# $blnCleanInput = $false
# }
# }
# }
# }
# Path... RegEx from http://regexlib.com/REDetails.aspx?regexp_id=2285
If ($blnCleanInput -eq $true)
{
$blnPathValid = ($_.Path `
-match "^((\\\\[a-zA-Z0-9-]+\\[a-zA-Z0-9`~!@#$%^&(){}'._-]+`
([ ]+[a-zA-Z0-9`~!@#$%^&(){}'._-]+)*)|([a-zA-Z]:))(\\[^ \\/:*?""<>|]+`
([ ]+[^ \\/:*?""<>|]+)*)*\\?$")
If ($blnPathValid -eq $false)
{
Trap {Continue;}
Throw "The share path in the CSV is not a valid Windows share path"
$blnCleanInput = $false
}
}
# RegEx from http://regexlib.com/REDetails.aspx?regexp_id=1145
# Share name can't contain : "/\[]:|<>+=;,?* can contain: ~`!@#$%^&()_-{}".
If ($blnCleanInput -eq $true)
{
$blnShareNameValid = ($_.Name `
-match "(^[A-Za-z0-9~`!@#$%_\^\&\-\.\ \(\)\{\}]{1,80})$")
If ($blnShareNameValid -eq $false)
{
Trap {Continue;}
Throw "The share name in the CSV is not a valid Windows share name"
$blnCleanInput = $false
}
}
##############################IMPORTANT if You want more ACCESS to be updated
# AccessMask: Read, Change, Full Control are the only access masks currently
#Add more AM if needed
If ($blnCleanInput -eq $true)
{
#ADD OR REMOVE ACCESS MASKS BASED ON YOUR PREFERENCES
If ( ($_.AccessMask -ne "1179817") `
-and ($_.AccessMask -ne "1245631") `
-and ($_.AccessMask -ne "2032127"))
{
Trap {Continue;}
Throw $_.AccessMask + " is an unsupported access mask"
$blnCleanInput = $false
}
}
# Ace Type: 0 is allow, 1 is deny
If ($blnCleanInput -eq $true) {
[int]$AceType = $_.AceType
If (($AceType -ne 0) -and ($AceType -ne 1)) {
Trap {Continue;}
Throw "Ace type must be 0 or 1"
$blnCleanInput = $false
}
}
#Ace Flags is a bit mask of values 1, 2, 4, 8, 16 therefore any combo 1 and 31
#http://msdn.microsoft.com/en-us/library/aa392711(v=VS.85).aspx
If ($blnCleanInput -eq $true) {
[int]$AceFlags = $_.AceFlags
If (($AceFlags -lt 0) -or ($AceFlags -gt 31)) {
Trap {Continue;}
Throw "Ace flags must be between 0 and 31"
$blnCleanInput = $false
}
}
} # End of $arrCSVShareInfo
Return $blnCleanInput
}
#End Function Check-CleanInput
Function Check-DoesSharePathExist($sharePath)
{
$pathExists = $null
$pathExists = Test-Path $SharePath
If ($PathExists -ne $true) {
return $false
}
Else {
Return $true
}
}
Function Check-DoesGroupExist($groupCN)
{
#grab all groups with GID's
$searchRoot = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($searchRoot)
$searcher.filter = "(&(objectClass=group)(CN=" + $groupCN + "))"
$searchResults = $searcher.findall()
If($searchResults.count -lt 1)
{$results = $false}
Else
{$results = $true}
$searchResults.Dispose()
$searcher.Dispose()
$searchResults = $null
$searcher = $null
Return $results
}
Function Check-DoesUserExist($sAMAccountName)
{
$searchRoot = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($searchRoot)
$searcher.filter = "(&(objectClass=person)`
(sAMAccountName=" + $sAMAccountName + "))"
$searchResults = $searcher.findall()
If($searchResults.count -lt 1)
{$results = $false}
Else
{$results = $true}
$searchResults.Dispose()
$searcher.Dispose()
$searchResults = $null
$searcher = $null
Return $results
}
Function Create-Folder($strFolder)
{
$results = $null
$results = $false
If($strFolder -eq $null -or $strFolder -eq "" -or $strFolder -eq $false)
{$results = $false}
Else
{
If((Test-Path $strFolder) -eq $true)
{$results = $true}
Else
{New-Item $strFolder -itemType Directory}
If((Test-Path $strFolder) -eq $true)
{$results = $true}
Else
{$results = $false}
}
Return $results
}
Function Get-SharePath($shareName)
{
Trap{continue;}
$strWMI = $null
$strWMI = "\\" + $fileserver + `
"\root\cimv2:win32_share.name='" + $shareName + "'"
$sharePath = $null
$sharePath = ([wmi]$strWMI).path
Return $sharePath
}
Function Check-DoesShareExist($shareName)
{
$shareExists = $null
$sharePath = $null
$sharePath = Get-SharePath $shareName
If($sharePath -eq $false -or $sharePath -eq $null)
{$shareExists = $false}
Else
{$shareExists = $true}
Return $shareExists
}
Function Check-SharePermissions($ShareName, $arrCSVShareInfo)
{
$strWMI = "\\" + $fileServer + `
"\root\cimv2:win32_LogicalShareSecuritySetting.Name='" + $ShareName + "'"
$objWMI_ShareSec = [wmi]$strWMI
$objWMI_SD = $objWMI_ShareSec.invokeMethod('GetSecurityDescriptor',$null,$null)
$numACEsMatched = 0
$ExistingShareDACL = $objWMI_SD.Descriptor.DACL
$DACLlength = $ExistingShareDACL.length
#Only compare CSV to current DACL if they are the same length
If ($arrCSVShareInfo.length -eq $DACLlength) {
$ExistingShareDACL | % {
For($i = 0;$i -lt $arrCSVShareInfo.length;$i++) {
#If aone of the ACE's is the same as 1 of the CSV entries
#in all categories, add 1 to the ACEsMatched
If(`
($_.AccessMask -eq $arrCSVShareInfo[$i].AccessMask)`
-and ($_.Trustee.Name -eq $arrCSVShareInfo[$i].User)`
-and ($_.Trustee.Domain -eq $arrCSVShareInfo[$i].Domain)`
-and ($_.AceFlags -eq $arrCSVShareInfo[$i].AceFlags)`
-and ($_.AceType -eq $arrCSVShareInfo[$i].AceType)) {
$numACEsMatched++
}
}
}
}
If ($numACEsMatched -eq $DACLlength) {
Return $true
}
Else {
Return $false
}
}
Function Fix-SharePermissions ($ShareName, $arrCSVShareInfo)
{
#Create security objects
$objWMI_NewSD = ([WMIClass] ("\\" + $FileServer + `
"\root\CIMv2:Win32_SecurityDescriptor")).CreateInstance()
$objWMI_NewSD.DACL = @()
$objWMI_NewEmptyACE = ([WMIClass] ("\\" + $FileServer + `
"\root\CIMv2:Win32_ACE")).CreateInstance()
$objWMI_NewTrustee = ([WMIClass] ("\\" + $FileServer + `
"\root\CIMv2:Win32_Trustee")).CreateInstance()
$arrCSVShareInfo | % {
#fill with CSV permissions
$objWMI_NewCompleteACE = `
(Add-PermissionsToACE $_ $objWMI_NewTrustee $objWMI_NewEmptyACE )
$objWMI_NewSD.DACL += $objWMI_NewCompleteACE.PsObject.BaseObject
}
$strWMI = "\\" + $fileServer + "\root\cimv2:win32_Share.Name='" + `
$ShareName + "'"
$objWMI_ThisShare = [wmi]$strWMI
$inParams = $objWMI_ThisShare.GetMethodParameters("SetShareInfo")
$inParams["Access"] = $objWMI_NewSD.PsObject.BaseObject
#attach new SD to share
$objWMI_ThisShare.InvokeMethod("SetShareInfo",$inParams,$null)
#Check if permissions are now right
$blnDoPermsMatch = Check-SharePermissions $ShareName $arrCSVShareInfo
Return $blnDoPermsMatch
}
Function VerifyAndFix-ShareInfo
{
[CmdletBinding()]
param($name, $path, $arrCSVShareInfo)
$blnerrorsdetected = $null
$blnErrorsDetected = $false
$strErrorMsg = $null
$blnCleanInput = Check-CleanInput $arrCSVShareInfo -EV err -EA SilentlyContinue
If ($blnCleanInput -eq $false) {
$blnErrorsDetected = $true
$strErrorMsg = $err
trap {Continue;}
throw $strErrorMsg
return $blnErrorsDetected
break
}
$blnPathExist = Check-DoesSharePathExist $path
If ($blnPathExist -eq $false) {
$blnPathExist = Create-Folder $Path
If ($blnPathExist -eq $false) {
$blnErrorsDetected = $true
$strErrorMsg = "The file path does not exist `
and could not be created"
trap {Continue;}
throw $strErrorMsg
return $blnErrorsDetected
break
}
}
# If Share Path exists, share exists
$blnShareExist = Check-DoesShareExist $name
If($blnShareExist -ne $false -and $blnShareExist -ne $false)
{
$blnDoPermsMatch = Check-SharePermissions $name $arrCSVShareInfo
If ($blnDoPermsMatch -eq $false) {
$blnDoPermsMatch = Fix-SharePermissions $name $arrCSVShareInfo
If ($blnDoPermsMatch -eq $false) {
$blnErrorsDetected = $true
$strErrorMsg = "The share exists, but `
the permissions do not match the CSV"
trap {Continue;}
throw $strErrorMsg
return $blnErrorsDetected
break
}
}
}
return $blnErrorsDetected
}
# End of Function VerifyAndFix-ShareInfo
Function Add-PermissionsToACE($arrCSVShareInfo, `
[System.Management.ManagementObject]$objWMI_Trustee, `
[System.Management.ManagementObject]$objWMI_ACE)
{
# Add properties to trustee
$objWMI_Trustee.Domain = $arrCSVShareInfo.Domain
$objWMI_Trustee.Name = $arrCSVShareInfo.Name
# Get SID, convert to binary.
# http://mow001.blogspot.com/2005/10/getting-and-using-securityprincipal.html
$strSID = ((new-object System.Security.Principal.NTAccount `
($arrCSVShareInfo.domain, $arrCSVShareInfo.user)`
).translate([System.Security.Principal.SecurityIdentifier]))
[byte[]]$binSID = ,0 * $strSID.BinaryLength
$strSID.GetBinaryForm($binSID,0)
$objWMI_Trustee.SID = $binSID
# Add properties to ACE
$objWMI_ACE.AccessMask = $arrCSVShareInfo.AccessMask
$objWMI_ACE.AceType = $arrCSVShareInfo.AceType
$objWMI_ACE.AceFlags = $arrCSVShareInfo.AceFlags
$objWMI_ACE.Trustee = $objWMI_Trustee.PsObject.BaseObject
Return $objWMI_ACE
}
Function Create-ShareFromCSVInfo($Name, $Path, $Description , `
[System.Management.ManagementObject]$SecurityDescriptor)
{
$results = $null
$objWMI_Share= [WMIClass]"Win32_Share"
#("\\" + $FileServer + "\root\CIMv2:Win32_Share" )
$InParams = $objWMI_Share.GetMethodParameters('Create')
# Fill parameters
$InParams["Access"] = $SecurityDescriptor.PsObject.BaseObject
$InParams["Description"] = $Description
$InParams["Name"] = $Name
#$InParams["Password"] = [string]
$InParams["Path"] = $Path
$InParams["Type"] = "0"
$R = $objWMI_Share.InvokeMethod('Create', $InParams, $null)
If ($R.ReturnValue -ne "0") {
#0 means success, anything else failed
$results = $false
}
Else {
$results = $true
}
Return $results
}
########### MAIN ###########
#This hash table will hold names of shares with errors.
$ProblemShares = @{}
$counter = $null
$arrCSVShareInfo = @()
For($counter = 0;$counter -le $sharelist.length;$counter++) {
If (($sharelist[$counter].name -eq $sharelist[$counter-1].name)`
-or ($counter -eq 0))
{
$arrCSVShareInfo += $sharelist[$counter]
}
ElseIf ((($sharelist[$counter].name -ne $sharelist[$counter-1].name)`
-and ($counter -ne 0)) -or ($counter -eq $sharelist.length))
{
$name = $sharelist[$counter-1].name
$path = $sharelist[$counter-1].path
$description = $sharelist[$counter-1].description
write-host "Processing :" $arrCSVShareInfo[0].name
# Pass each share through verification process,
#failed shares have error message stored in $err
$blnErrorsDetected = `
VerifyAndFix-ShareInfo $Name $Path $arrCSVShareInfo -EV err -EA SilentlyContinue
#Check if share exists, only want to create it if it does not exist
$blnShareExists = $null
$blnShareExists = Check-DoesShareExist $name
#Only want to create it if there were no errors
If ($blnErrorsDetected -eq $true)
{
trap {continue;}
$ProblemShares.Add($name, $err)
}
ElseIf ($blnShareExists -eq $false)
{
#Create Security Objects
$objWMI_SD = ([WMIClass] ("\\" + $FileServer + `
"\root\CIMv2:Win32_SecurityDescriptor")).CreateInstance()
$objWMI_SD.DACL = @()
$objWMI_EmptyACE = `
([WMIClass] ("\\" + $FileServer + "\root\CIMv2:Win32_ACE")).CreateInstance()
$objWMI_Trustee = `
([WMIClass] ("\\" + $FileServer + "\root\CIMv2:Win32_Trustee")).CreateInstance()
$arrCSVShareInfo | `
% {
$objWMI_CompleteACE = `
(Add-PermissionsToACE $_ $objWMI_Trustee $objWMI_EmptyACE )
$objWMI_SD.DACL += $objWMI_CompleteACE.PsObject.BaseObject
}
$blnShareCreated = `
Create-ShareFromCSVinfo $Name $Path $Description $objWMI_SD
If ($blnShareCreated -eq $false)
{
$ProblemShares.Add($name, "Share Creation Failed")
}
}
#Make a new array for the next share
$arrCSVShareInfo = @()
$arrCSVShareInfo += $sharelist[$counter]
}
}
Write-Host "Import Complete" -ForegroundColor green
If ($problemShares.count -ge 1)
{
Write-Host "These Shares Failed to Import:"
#Write the failed shares to the screen, complete with detailed error messages
$ProblemShares | fl *
}
}
## end of if(($mode -match "Import") -or ($mode -match "import"))
} ## End of try block
catch
{
Write-Host -ForegroundColor Red "$mode was not successfull "
}
## End of catch block
}
# End of function