-
Notifications
You must be signed in to change notification settings - Fork 4
/
Get-CMUnusedSources.ps1
1761 lines (1573 loc) · 78.8 KB
/
Get-CMUnusedSources.ps1
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#PSScriptInfo
.VERSION 1.0.8
.GUID 62980d1d-d263-4c01-b49c-e64502363127
.AUTHOR Adam Cook (Twitter: @codaamok - website: cookadam.co.uk)
.COMPANYNAME
.COPYRIGHT
.TAGS SCCM ConfigMgr ConfigurationManager MEMCM MECM
.LICENSEURI https://github.com/codaamok/Get-CMUnusedSources/blob/master/LICENSE
.PROJECTURI https://github.com/codaamok/Get-CMUnusedSources
.ICONURI
.EXTERNALMODULEDEPENDENCIES ImportExcel
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
#>
<#
.SYNOPSIS
Get-CMUnusedSources will tell you what folders are not used by ConfigMgr in a given path. See https://github.com/codaamok/Get-CMUnusedSources for documentation.
.DESCRIPTION
This script will tell you what folders are used or not used in a given path by a site in System Center Configuration Manager.
It leverages the ConfigMgr PowerShell cmdlets to gather content object source path information so you need the console installed. The script can be run remotely from a site server, e.g. your desktop.
A PSObject is returned with the UsedBy status of each folder under the given parameter -SourcesLocation. You can also specify -ExcelReport generated by the module ImportExcel, from there you can export to PDF, CSV or XLSX.
See the GitHub repository README for the documentation https://github.com/codaamok/Get-CMUnusedSources and my blog with a personal account of me writing this script https://www.cookadam.co.uk/get-cmunusedsources.
.PARAMETER SourcesLocation
The path to the directory you store your ConfigMgr sources. Can be a UNC or local path. Must be a valid path that you have read access to.
.PARAMETER SiteServer
The site server of the given ConfigMgr site code. The server must be reachable over a network.
.PARAMETER SiteCode
The site code of the ConfigMgr site you wish to query for content objects.
.PARAMETER ExcludeFolders
An array of folders that you want to exclude the script from checking, which should be absolute paths under the path given for -SourcesLocation.
.PARAMETER Packages
Specify this switch to include Packages within the search to determine unused content on disk.
.PARAMETER Applications
Specify this switch to include Applications within the search to determine unused content on disk.
.PARAMETER Drivers
Specify this switch to include Drivers within the search to determine unused content on disk.
.PARAMETER DriverPackages
Specify this switch to include DriverPackages within the search to determine unused content on disk.
.PARAMETER OSImages
Specify this switch to include OSImages within the search to determine unused content on disk.
.PARAMETER OSUpgradeImages
Specify this switch to include OSUpgradeImages within the search to determine unused content on disk.
.PARAMETER BootImages
Specify this switch to include BootImages within the search to determine unused content on disk.
.PARAMETER DeploymentPackages
Specify this switch to include DeploymentPackages within the search to determine unused content on disk.
.PARAMETER AltFolderSearch
Specify this if you suspect there are issue with the default mechanism of gathering folders, which is:
Get-ChildItem -LiteralPath "\\?\UNC\server\share\folder" -Directory -Recurse | Select-Object -ExpandProperty FullName
.PARAMETER NoProgress
Specify this to disable use of Write-Progress.
.PARAMETER Log
Specify this to enable logging. The log file(s) will be saved to the same directory as this script with a name of <scriptname>_<datetime>.log. Rolled log files will follow a naming convention of <filename>_1.lo_ where the int increases for each rotation. Each maximum log file is 2MB.
.PARAMETER ExportReturnObject
Specify this option if you wish to export the PowerShell return object to an XML file. The XML file be saved to the same directory as this script with a name of <scriptname>_<datetime>_result.xml. It can easily be reimported using Import-Clixml cmdlet.
.PARAMETER ExportCMContentObjects
Specify this option if you wish to export all ConfigMgr content objects to an XML file. The XML file be saved to the same directory as this script with a name of <scriptname>_<datetime>_cmobjects.xml. It can easily be reimported using Import-Clixml cmdlet.
.PARAMETER ExcelReport
Specify this option to enable the generation for an Excel report of the result. Doing this will force you to have the ImportExcel module installed. For more information on ImportExcel: https://github.com/dfinke/ImportExcel. The .xlsx file will be saved to the same directory as this script with a name of <scriptname>_<datetime>.xlsx.
.PARAMETER Threads
Set the number of threads you wish to use for concurrent processing of this script. Default value is number of processes from env var NUMBER_OF_PROCESSORS.
.INPUTS
.OUTPUTS
.EXAMPLE
C:\> $result = .\Get-CMUnusedSources.ps1 -SourcesLocation \\sccm\Applications$ -SiteServer SCCM -Applications -Log -LogFileSize 10MB -NumOfRotatedLogs 5 -ExportReturnObject -ExcelReport -Threads 2
.EXAMPLE
C:\> $result = .\Get-CMUnusedSources.ps1 -SourcesLocation F:\ -SiteServer SCCM -Log -ExcelReport
.NOTES
Author: Adam Cook (@codaamok)
License: GLP-3.0
Source: https://github.com/codaamok/Get-CMUnusedSources
#>
#Requires -Version 5.1
Param (
[Parameter(Mandatory=$true, Position = 0, HelpMessage="Valid path (local or remote0 to where you store you ConfigMgr sources.")]
[ValidateScript({
if (!([System.IO.Directory]::Exists($_))) {
throw "Invalid path or access denied"
} elseif (!($_ | Test-Path -PathType Container)) {
throw "Value must be a directory, not a file"
} else {
return $true
}
})]
[string]$SourcesLocation,
[Parameter(Mandatory=$true, Position = 1, HelpMessage="ConfigMgr site server of the site site code.")]
[ValidateScript({
if (!(Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue)) {
throw "Host `"$($_)`" is unreachable"
} else {
return $true
}
})]
[string]$SiteServer,
[Parameter(Mandatory=$false, Position = 2, HelpMessage="ConfigMgr site code you are querying.")]
[ValidatePattern('^[a-zA-Z0-9]{3}$')]
[string]$SiteCode,
[Parameter(Mandatory=$false, HelpMessage="An array of folders to exclude under -SourcesLocation.")]
[string[]]$ExcludeFolders,
[Parameter(Mandatory=$false, HelpMessage="Gather packages.")]
[switch]$Packages,
[Parameter(Mandatory=$false, HelpMessage="Gather applications.")]
[switch]$Applications,
[Parameter(Mandatory=$false, HelpMessage="Gather drivers.")]
[switch]$Drivers,
[Parameter(Mandatory=$false, HelpMessage="Gather driver packages.")]
[switch]$DriverPackages,
[Parameter(Mandatory=$false, HelpMessage="Gather Operating System images.")]
[switch]$OSImages,
[Parameter(Mandatory=$false, HelpMessage="Gather Operating System upgrade images.")]
[switch]$OSUpgradeImages,
[Parameter(Mandatory=$false, HelpMessage="Gather boot images.")]
[switch]$BootImages,
[Parameter(Mandatory=$false, HelpMessage="Gather deployment packages.")]
[switch]$DeploymentPackages,
[Parameter(Mandatory=$false, HelpMessage="Enable alternative folder search.")]
[switch]$AltFolderSearch,
[Parameter(Mandatory=$false, HelpMessage="Disable use of Write-Progress.")]
[switch]$NoProgress,
[Parameter(Mandatory=$false, HelpMessage="Enable logging.")]
[switch]$Log,
[Parameter(Mandatory=$false, HelpMessage="Generate XML export of PowerShell object with the result.")]
[switch]$ExportReturnObject,
[Parameter(Mandatory=$false, HelpMessage="Generate XML export of PowerShell object with all ConfigMgr content objects.")]
[switch]$ExportCMContentObjects,
[Parameter(Mandatory=$false, HelpMessage="Generate Excel report of the result.")]
[switch]$ExcelReport,
[Parameter(Mandatory=$false, HelpMessage="Number of threads to use for execution.")]
[int32]$Threads = $env:NUMBER_OF_PROCESSORS
)
<#
TODO:
- $SiteServer should be validated - omg stupid hard
- Exclude folders parameter in get-childitem?
- publish to technet
- delete log entries for $result??
- if given F:\ or \\server\f$ currently Get-AllPaths does not determine shared folders that match the path used
#>
#region Define PSDefaultParameterValues and other variables
$JobId = Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'
$StartTime = Get-Date
$PSDefaultParameterValues = @{
"Write-CMLogEntry:Bias" = (Get-CimInstance -ClassName Win32_TimeZone | Select-Object -ExpandProperty Bias)
"Write-CMLogEntry:Folder" = ($PSCommandPath | Split-Path -Parent)
"Write-CMLogEntry:FileName" = (($PSCommandPath | Split-Path -Leaf) + "_" + $JobId + ".log")
"Write-CMLogEntry:Enable" = $Log.IsPresent
"Write-CMLogEntry:MaxLogFileSize" = 2MB
"Write-CMLogEntry:MaxNumOfRotatedLogs" = 0
"Write-ScreenInfo:ScriptStart" = $StartTime
"Export-Excel:TableStyle" = "Medium20"
"Add-ExcelTable:TableStyle" = "Medium20"
"Export-Excel:AutoSize" = $true
"Export-Excel:AutoFilter" = $true
"Export-Excel:ErrorACtion" = "Stop"
"Add-Worksheet:ErrorACtion" = "Stop"
"Set-ExcelRange:ErrorACtion" = "Stop"
"Remove-Worksheet:ErrorACtion" = "Stop"
"Close-ExcelPackage:ErrorACtion" = "Stop"
"Export-Excel:ErrorVariable" = "NewExcelReportErr"
"Add-Worksheet:ErrorVariable" = "NewExcelReportErr"
"Set-ExcelRange:ErrorVariable" = "NewExcelReportErr"
"Remove-Worksheet:ErrorVariable" = "NewExcelReportErr"
"Close-ExcelPackage:ErrorVariable" = "NewExcelReportErr"
}
#endregion
#region Define functions
Function Write-CMLogEntry {
<#
.SYNOPSIS
Write to log file in CMTrace friendly format.
.DESCRIPTION
Half of the code in this function is Cody Mathis's. I added log rotation and some other bits, with help of Chris Dent for some sorting and regex. Should find this code on the WinAdmins GitHub repo for configmgr.
.OUTPUTS
Writes to $Folder\$FileName and/or standard output.
.LINK
https://github.com/winadminsdotorg/SystemCenterConfigMgr
#>
param (
[parameter(Mandatory = $true, HelpMessage = 'Value added to the log file.')]
[ValidateNotNullOrEmpty()]
[string]$Value,
[parameter(Mandatory = $false, HelpMessage = 'Severity for the log entry. 1 for Informational, 2 for Warning and 3 for Error.')]
[ValidateNotNullOrEmpty()]
[ValidateSet('1', '2', '3')]
[string]$Severity = 1,
[parameter(Mandatory = $false, HelpMessage = "Stage that the log entry is occuring in, log refers to as 'component'.")]
[ValidateNotNullOrEmpty()]
[string]$Component,
[parameter(Mandatory = $true, HelpMessage = 'Name of the log file that the entry will written to.')]
[ValidateNotNullOrEmpty()]
[string]$FileName,
[parameter(Mandatory = $true, HelpMessage = 'Path to the folder where the log will be stored.')]
[ValidateNotNullOrEmpty()]
[string]$Folder,
[parameter(Mandatory = $false, HelpMessage = 'Set timezone Bias to ensure timestamps are accurate.')]
[ValidateNotNullOrEmpty()]
[int32]$Bias,
[parameter(Mandatory = $false, HelpMessage = 'Maximum size of log file before it rolls over. Set to 0 to disable log rotation.')]
[ValidateNotNullOrEmpty()]
[int32]$MaxLogFileSize = 0,
[parameter(Mandatory = $false, HelpMessage = 'Maximum number of rotated log files to keep. Set to 0 for unlimited rotated log files.')]
[ValidateNotNullOrEmpty()]
[int32]$MaxNumOfRotatedLogs = 0,
[parameter(Mandatory = $true, HelpMessage = 'A switch that enables the use of this function.')]
[ValidateNotNullOrEmpty()]
[switch]$Enable
)
if ($Enable.IsPresent -eq $true) {
# Determine log file location
$LogFilePath = Join-Path -Path $Folder -ChildPath $FileName
if ((([System.IO.FileInfo]$LogFilePath).Exists) -And ($MaxLogFileSize -ne 0)) {
# Get log size in bytes
$LogFileSize = [System.IO.FileInfo]$LogFilePath | Select-Object -ExpandProperty Length
if ($LogFileSize -ge $MaxLogFileSize) {
# Get log file name without extension
$LogFileNameWithoutExt = $FileName -replace ([System.IO.Path]::GetExtension($FileName))
# Get already rolled over logs
$RolledLogs = "{0}_*" -f $LogFileNameWithoutExt
$AllLogs = Get-ChildItem -Path $Folder -Name $RolledLogs -File
# Sort them numerically (so the oldest is first in the list)
$AllLogs = $AllLogs | Sort-Object -Descending { $_ -replace '_\d+\.lo_$' }, { [Int]($_ -replace '^.+\d_|\.lo_$') }
ForEach ($Log in $AllLogs) {
# Get log number
$LogFileNumber = [int32][Regex]::Matches($Log, "_([0-9]+)\.lo_$").Groups[1].Value
switch (($LogFileNumber -eq $MaxNumOfRotatedLogs) -And ($MaxNumOfRotatedLogs -ne 0)) {
$true {
# Delete log if it breaches $MaxNumOfRotatedLogs parameter value
$DeleteLog = Join-Path $Folder -ChildPath $Log
[System.IO.File]::Delete($DeleteLog)
}
$false {
# Rename log to +1
$Source = Join-Path -Path $Folder -ChildPath $Log
$NewFileName = $Log -replace "_([0-9]+)\.lo_$",("_{0}.lo_" -f ($LogFileNumber+1))
$Destination = Join-Path -Path $Folder -ChildPath $NewFileName
[System.IO.File]::Copy($Source, $Destination, $true)
}
}
}
# Copy main log to _1.lo_
$NewFileName = "{0}_1.lo_" -f $LogFileNameWithoutExt
$Destination = Join-Path -Path $Folder -ChildPath $NewFileName
[System.IO.File]::Copy($LogFilePath, $Destination, $true)
# Blank the main log
$StreamWriter = [System.IO.StreamWriter]::new($LogFilePath, $false)
$StreamWriter.Close()
}
}
# Construct time stamp for log entry
switch -regex ($Bias) {
'-' {
$Time = [string]::Concat($(Get-Date -Format 'HH:mm:ss.fff'), $Bias)
}
Default {
$Time = [string]::Concat($(Get-Date -Format 'HH:mm:ss.fff'), '+', $Bias)
}
}
# Construct date for log entry
$Date = (Get-Date -Format 'MM-dd-yyyy')
# Construct context for log entry
$Context = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
# Construct final log entry
$LogText = [string]::Format('<![LOG[{0}]LOG]!><time="{1}" date="{2}" component="{3}" context="{4}" type="{5}" thread="{6}" file="">', $Value, $Time, $Date, $Component, $Context, $Severity, $PID)
# Add value to log file
try {
$StreamWriter = [System.IO.StreamWriter]::new($LogFilePath, 'Append')
$StreamWriter.WriteLine($LogText)
$StreamWriter.Close()
}
catch [System.Exception] {
Write-Warning -Message ("Unable to append log entry to {0} file. Error message: {1}" -f $FileName, $_.Exception.Message)
}
}
}
Function Write-ScreenInfo {
[CmdletBinding()]
<#
.SYNOPSIS
Inspired by PSLog in the AutomatedLab module
https://github.com/AutomatedLab/AutomatedLab/blob/c01e2458e38811ccc4b2c58e3f958d666c39d9b9/PSLog/PSLog.psm1
#>
Param(
[Parameter(Mandatory = $true, Position = 0)]
[string[]]$Message,
[Parameter(Mandatory = $true)]
[datetime]$ScriptStart,
[Parameter(Mandatory = $false)]
[ValidateSet("Error", "Warning", "Info", "Verbose", "Debug")]
[string]$Type = "Info",
[Parameter(Mandatory = $false)]
[int32]$Indent = 0
)
$Date = Get-Date
$TimeString = "{0:d2}:{1:d2}:{2:d2}" -f $Date.Hour, $Date.Minute, $Date.Second
$TimeDelta = $Date - $ScriptStart
$TimeDeltaString = "{0:d2}:{1:d2}:{2:d2}" -f $TimeDelta.Hours, $TimeDelta.Minutes, $TimeDelta.Seconds
ForEach ($Msg in $Message) {
$Msg = ("- " + $Msg).PadLeft(($Msg.Length) + ($Indent * 4), " ")
$string = "[ {0} | {1} ] {2}" -f $TimeString, $TimeDeltaString, $Msg
switch ($Type) {
"Error" {
Write-Host $string -ForegroundColor Red
}
"Warning" {
Write-Host $string -ForegroundColor Yellow
}
"Info" {
Write-Host $string
}
"Debug" {
if ($DebugPreference -eq "Continue") { Write-Host $string -ForegroundColor Cyan }
}
"Verbose" {
if ($VerbosePreference -eq "Continue") { Write-Host $string -ForegroundColor Cyan }
}
}
}
}
Function Get-CMContent {
[CmdletBinding()]
<#
.SYNOPSIS
Get all ConfigMgr objects that can hold content, i.e. content objects.
.DESCRIPTION
Using the ConfigMgr PoSH cmdlets, in the $Commands array, get all content objects and filter them to the given site code.
For each content object, create a PSCustomObject with the needed properties.
Called by main body.
.OUTPUTS
System.Object.PSCustomObject
#>
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$Commands,
[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$SiteServer,
[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$SiteCode
)
Begin {
$CMPSSuppressFastNotUsedCheck = $true
[hashtable]$ShareCache = @{}
}
Process {
ForEach ($Command in $Commands) {
Write-CMLogEntry -Value ("Gathering: {0}" -f $Command -replace "Get-CM") -Severity 1 -Component "GatherContentObjects"
# Filter by site code
$Command = $Command + " | Where-Object SourceSite -eq `"{0}`"" -f $SiteCode
ForEach ($item in (Invoke-Expression $Command)) {
switch -regex ($Command) {
"^Get-CMApplication.+" {
$AppMgmt = [xml]$item.SDMPackageXML | Select-Object -ExpandProperty AppMgmtDigest
$Retired = $item | Select-Object -ExpandProperty IsExpired
ForEach ($DeploymentType in $AppMgmt.DeploymentType) {
$SourcePaths = $DeploymentType.Installer.Contents.Content.Location
# Using ForEach-Object because even if $SourcePaths is null, it will iterate null once which is ideal here where deployment types can have no source path.
# Also, A deployment type can have more than 1 source path: for install and uninstall paths
$SourcePaths | ForEach-Object {
$SourcePath = $_
# Get every possible path
$GetAllPathsResult = Get-AllPaths -Path $SourcePath -Cache $ShareCache -SiteServer $SiteServer
# Create content object PSObject with needed properties and add to array
$obj = [ordered]@{
ContentType = "Application"
UniqueID = $DeploymentType | Select-Object -ExpandProperty LogicalName
Name = "{0}::{1}" -f $item.LocalizedDisplayName,$DeploymentType.Title.InnerText
IsRetired = $Retired
SourcePath = $SourcePath
SourcePathFlag = [int](Test-FileSystemAccess -Path $SourcePath -Rights Read)
AllPaths = $GetAllPathsResult[1]
}
if ($obj["SourcePathFlag"] -eq 0) {
$obj.Add("SizeMB", (Measure-ChildItem -Path $obj["SourcePath"] -Unit MB -Digits 2 | Select-Object -ExpandProperty Size))
}
else {
$obj.Add("SizeMB", $null)
}
[PSCustomObject]$obj
}
# Maintaining cache of shared folders for servers encountered so far
$ShareCache = $GetAllPathsResult[0]
Write-CMLogEntry -Value ("{0} - {1} - {2} - {3} - {4} - {5} - {6}" -f $obj.ContentType,$obj.UniqueID,$obj.Name,$obj.SourcePath,$obj.SourcePathFlag,[String]::Join(", ", @($obj.AllPaths.Keys)),$obj.SizeMB) -Severity 1 -Component "GatherContentObjects"
}
}
"^Get-CMDriver\s.+" {
$SourcePath = $item.ContentSourcePath
# Get every possible path
$GetAllPathsResult = Get-AllPaths -Path $SourcePath -Cache $ShareCache -SiteServer $SiteServer
# Create content object PSObject with needed properties and add to array
$obj = [ordered]@{
ContentType = "Driver"
UniqueID = $item.CI_ID
Name = $item.LocalizedDisplayName
IsRetired = "n/a"
SourcePath = $SourcePath
SourcePathFlag = [int](Test-FileSystemAccess -Path $SourcePath -Rights Read)
AllPaths = $GetAllPathsResult[1]
}
if ($obj["SourcePathFlag"] -eq 0) {
$obj.Add("SizeMB", (Measure-ChildItem -Path $obj["SourcePath"] -Unit MB -Digits 2 | Select-Object -ExpandProperty Size))
}
else {
$obj.Add("SizeMB", $null)
}
[PSCustomObject]$obj
# Maintaining cache of shared folders for servers encountered so far
$ShareCache = $GetAllPathsResult[0]
Write-CMLogEntry -Value ("{0} - {1} - {2} - {3} - {4} - {5} - {6}" -f $obj.ContentType,$obj.UniqueID,$obj.Name,$obj.SourcePath,$obj.SourcePathFlag,[String]::Join(", ", @($obj.AllPaths.Keys)),$obj.SizeMB) -Severity 1 -Component "GatherContentObjects"
}
default {
# OS images and boot iamges are absolute paths to files
if (($Command -match ("^Get-CMOperatingSystemImage.+")) -Or ($Command -match ("^Get-CMBootImage.+"))) {
$SourcePath = Split-Path $item.PkgSourcePath
}
else {
$SourcePath = $item.PkgSourcePath
}
$ContentType = ([Regex]::Matches($Command, "Get-CM([^\s]+)")).Groups[1].Value
# Get every possible path
$GetAllPathsResult = Get-AllPaths -Path $SourcePath -Cache $ShareCache -SiteServer $SiteServer
# Create content object PSObject with needed properties and add to array
$obj = [ordered]@{
ContentType = $ContentType
UniqueID = $item.PackageId
Name = $item.Name
IsRetired = "n/a"
SourcePath = $SourcePath
SourcePathFlag = [int](Test-FileSystemAccess -Path $SourcePath -Rights Read)
AllPaths = $GetAllPathsResult[1]
}
if ($obj["SourcePathFlag"] -eq 0) {
$obj.Add("SizeMB", (Measure-ChildItem -Path $obj["SourcePath"] -Unit MB -Digits 2 | Select-Object -ExpandProperty Size))
}
else {
$obj.Add("SizeMB", $null)
}
[PSCustomObject]$obj
# Maintaining cache of shared folders for servers encountered so far
$ShareCache = $GetAllPathsResult[0]
Write-CMLogEntry -Value ("{0} - {1} - {2} - {3} - {4} - {5} - {6}" -f $obj.ContentType,$obj.UniqueID,$obj.Name,$obj.SourcePath,$obj.SourcePathFlag,[String]::Join(", ", @($obj.AllPaths.Keys)),$obj.SizeMB) -Severity 1 -Component "GatherContentObjects"
}
}
}
Write-CMLogEntry -Value ("Done gathering: {0}" -f ($Command -replace "Get-CM").Split(" ")[0]) -Severity 1 -Component "GatherContentObjects"
}
}
}
Function Get-AllPaths {
<#
.SYNOPSIS
Determine all possible paths for a given path.
.DESCRIPTION
For a given path, determine all other possible path combinations that ultimately point back to $Path.
Useful to determine the local path for a given UNC path (in turn get the UNC path that uses the drive $ share), or if a there are multiple shared folders pointing to the same location.
Called by Get-CMContent.
.OUTPUTS
System.Object.List with always only two elements; $AllPaths (hashtable, the calculated list of "all paths" for the given $Path), and $Cache (hashtable, the shared folders cache).
The first element ($Cache, hashtable) of the $result collection is dedicated to being a cache which will contain a list of all servers (key) and a hashtable (value) for a list of shared folder names and their local paths.
The second element ($AllPath, hashtable) of the $result collection contains the list of all possible paths associated with the given $Path (key) and the NetBIOS server name (value) of which it belongs to.
.EXAMPLE
PS C:\> Get-AllPaths -Path "\\SCCM\Applications$\7-zip" -Cache $SharedFolderCache -SiteServer "SCCM"
Name Value
---- -----
192.168.175.11 {Folder, UpdateServicesPackages, EasySetupPayload, SMSSIG$...}
sccm {Folder, UpdateServicesPackages, EasySetupPayload, SMSSIG$...}
sccm.acc.local {Folder, UpdateServicesPackages, EasySetupPayload, SMSSIG$...}
\\192.168.175.11\Applications$ sccm
\\192.168.175.11\F$\Applica... sccm
\\sccm.acc.local\Applications$ sccm
\\sccm\Applications$ sccm
\\sccm\DiffFolder1$ sccm
\\sccm.acc.local\F$\Applica... sccm
\\192.168.175.11\DiffFolder1$ sccm
F:\Applications sccm
\\sccm.acc.local\DiffFolder1$ sccm
\\sccm\F$\Applications sccm
#>
param (
[string]$Path,
[hashtable]$Cache,
[string]$SiteServer
)
[System.Collections.Generic.List[Object]]$result = @()
[hashtable]$AllPaths = @{}
if (([string]::IsNullOrEmpty($Path) -eq $false) -And ($Path -notmatch "^[a-zA-Z]:\\$")) {
$Path = $Path.TrimEnd("\")
}
##### Determine path type
switch ($true) {
($Path -match "^\\\\([a-zA-Z0-9`~!@#$%^&(){}\'._-]+)\\([a-zA-Z]\$)$") {
# Path that is \\server\f$
$Server,$ShareName,$ShareRemainder = $Matches[1],$Matches[2],$null
$PathType = 4
break
}
($Path -match "^\\\\([a-zA-Z0-9`~!@#$%^&(){}\'._-]+)\\([a-zA-Z]\$)(\\[a-zA-Z0-9`~\\!@#$%^&(){}\'._ -]+)") {
# Path that is \\server\f$\folder
$Server,$ShareName,$ShareRemainder = $Matches[1],$Matches[2],$Matches[3]
$PathType = 3
break
}
($Path -match "^\\\\([a-zA-Z0-9`~!@#$%^&(){}\'._-]+)\\([a-zA-Z0-9`~!@#$%^&(){}\'._ -]+)$") {
# Path that is \\server\share
$Server,$ShareName,$ShareRemainder = $Matches[1],$Matches[2],$null
$PathType = 2
break
}
($Path -match "^\\\\([a-zA-Z0-9`~!@#$%^&(){}\'._-]+)\\([a-zA-Z0-9`~!@#$%^&(){}\'._ -]+)(\\[a-zA-Z0-9`~\\!@#$%^&(){}\'._ -]+)") {
# Path that is \\server\share\folder
$Server,$ShareName,$ShareRemainder = $Matches[1],$Matches[2],$Matches[3]
$PathType = 1
break
}
($Path -match "^[a-zA-Z]:\\") {
# Path that is local
# Script does not determine UNC / shared folder paths if the content object source path is a local path
$AllPaths.Add($Path, $SiteServer)
$result.Add($Cache)
$result.Add($AllPaths)
return $result
}
([string]::IsNullOrEmpty($Path) -eq $true) {
# If there is no source path, just return now with $AllPaths empty
$result.Add($Cache)
$result.Add($AllPaths)
return $result
}
default {
# Please share $Path with me if this is caught!
# As a fail safe, abort
$Message = "Unable to interpret path `"{0}`"" -f $Path
Write-ScreenInfo -Message $Message -Type "Warning" -Indent 1
Write-CMLogEntry -Value $Message -Severity 2 -Component "GatherContentObjects"
$AllPaths.Add($Path, $null)
$result.Add($Cache)
$result.Add($AllPaths)
return $result
}
}
##### Determine FQDN, IP and NetBIOS
# Only determine if you have a record
# Might be annoying if $Server is an IP, unreachable and revese lookup succeeds
if (Test-Connection -ComputerName $Server -Count 1 -ErrorAction SilentlyContinue) {
if ($Server -as [IPAddress]) {
try {
# Reverse lookup
$FQDN = [System.Net.Dns]::GetHostEntry($Server) | Select-Object -ExpandProperty HostName
$NetBIOS = $FQDN.Split(".")[0]
}
catch {
# In case no record
$FQDN = $null
}
$IP = $Server
}
else {
try {
# Get FQDN even if $Server is FQDN, so we cut out $NetBIOS and resolve for $IP
$FQDN = [System.Net.Dns]::GetHostByName($Server) | Select-Object -ExpandProperty HostName
$NetBIOS = $FQDN.Split(".")[0]
}
catch {
# In case no record
$FQDN = $null
}
$IP = (((Test-Connection $Server -Count 1 -ErrorAction SilentlyContinue)).IPV4Address).IPAddressToString
}
}
else {
# Won't be able to query Win32_Class if unreachable so no point continuing
Write-CMLogEntry -Value ("Server `"{0}`" is unreachable" -f $Server) -Severity 2 -Component "GatherContentObjects"
$AllPaths.Add($Path, $null)
$result.Add($Cache)
$result.Add($AllPaths)
return $result
}
##### Update the cache of shared folders and their local paths
if (($Cache.Keys -contains $FQDN) -eq $false) {
# Do not yet have this server's shares cached
# $AllSharedFolders is null if couldn't connect to serverr to get all shared folders
$AllSharedFolders = Get-AllSharedFolders -Server $FQDN
If ($AllSharedFolders -is [Hashtable] -And ($AllSharedFolders.count -gt 0)) {
$NetBIOS,$FQDN,$IP | ForEach-Object {
if ([String]::IsNullOrEmpty($_) -eq $true) {
continue
}
else {
$Cache.Add($_, $AllSharedFolders)
}
}
}
else {
# Add null so on the next encounter of a server from a given UNC path, we don't wastefully try again
$NetBIOS,$FQDN,$IP | ForEach-Object {
if ([String]::IsNullOrEmpty($_) -eq $true) {
continue
}
else {
$Cache.Add($_, $null)
}
}
}
}
##### Build the AllPaths property
[System.Collections.Generic.List[String]]$AllPathsArr = @()
$NetBIOS,$FQDN,$IP | ForEach-Object -Process {
if ([String]::IsNullOrEmpty($_) -eq $true) {
continue
}
else {
$AltServer = $_
if ($null -ne $Cache.$AltServer) {
# Get the share's local path
$LocalPath = $Cache.$AltServer[$ShareName]
}
else {
$LocalPath = $null
}
# If \\server\f$ then $LocalPath is "F:"
if ([string]::IsNullOrEmpty($LocalPath) -eq $false) {
if ($PathType -match "1|2") {
# Add \\server\f$\path\to\shared\folder\on\disk
$AllPathsArr.Add(("\\$($AltServer)\$($LocalPath)$($ShareRemainder)" -replace ':', '$'))
# Get other shared folders that point to the same path and add them to the AllPaths array
$SharesWithSamePath = $Cache.$AltServer.GetEnumerator().Where( { $_.Value -eq $LocalPath } ) | Select-Object -ExpandProperty Key
ForEach ($AltShareName in $SharesWithSamePath) {
$AllPathsArr.Add("\\$($AltServer)\$($AltShareName)$($ShareRemainder)")
}
}
}
else {
Write-CMLogEntry -Value ("Could not resolve share `"{0}`" on `"{1}`" from cache, either because it does not exist or could not query Win32_Share on server" -f $ShareName,$_) -Severity 2 -Component "GatherContentObjects"
}
# Add the original path again but with the alternate server (FQDN / NetBIOS / IP)
$AllPathsArr.Add("\\$($AltServer)\$($ShareName)$($ShareRemainder)")
}
} -End {
if ([string]::IsNullOrEmpty($LocalPath) -eq $false) {
# Either of the below are important in case user is running local to site server and gave local path as $SourcesLocation
if (($LocalPath -match "^[a-zA-Z]:$") -And ($PathType -match "2|4")) {
# Match if just a drive letter (WHY?!) and add it to AllPaths array
# This occurs if path type is 2 and the share points to root of a volume
$AllPathsArr.Add("$($LocalPath)\")
}
else {
# Add the local path to AllPaths array
$AllPathsArr.Add("$($LocalPath)$($ShareRemainder)")
}
}
}
# Add all that's inside the AllPaths array to the AllPaths hashtable
# Unfotunately adding stuff to hash table that already exists in there can be noisy to stderr in console
ForEach ($item in $AllPathsArr) {
if (($AllPaths.Keys -notcontains $item) -eq $true) {
$AllPaths.Add($item, $NetBIOS)
}
}
$result.Add($Cache)
$result.Add($AllPaths)
return $result
}
Function Get-AllSharedFolders {
<#
.SYNOPSIS
Get all shared folders hosted on a server.
.DESCRIPTION
Query Win32_Share WMI class on $Server and return a hashtable result.
Called by Get-AllPaths.
.OUTPUTS
System.Object.Hashtable where a list of shared folder names (key) and their local paths (value).
#>
Param([String]$Server)
[hashtable]$AllShares = @{}
$GetCimInstanceSplat = @{
ClassName = "Win32_Share"
ErrorAction = "Stop"
ErrorVariable = "GetCimInstanceErr"
}
# Get-CimInstance uses WinRM if ComputerName is provided, which can throw access denied if console is elevated
# I would rather the below be in place rather than unnecessarily requiring elevated console
if ([System.Net.Dns]::GetHostEntry($env:COMPUTERNAME).HostName -ne $Server) {
$GetCimInstanceSplat.Add("ComputerName", $Server)
}
try {
$Shares = (Get-CimInstance @GetCimInstanceSplat).Where( {-not [string]::IsNullOrEmpty($_.Path)} )
ForEach ($Share in $Shares) {
# The TrimEnd method is only really concerned for drive letter shares
# as they're usually stored as f$ = "F:\" and this messes up Get-AllPaths a little
$AllShares.Add($Share.Name, $Share.Path.TrimEnd("\"))
}
}
catch {
$Message = "Could not query Win32_Share on `"{0}`" ({1})" -f $Server, $GetCimInstanceErr.Message
Write-ScreenInfo -Message $Message -Type "Warning" -Indent 1
Write-CMLogEntry -Value $Message -Severity 2 -Component "GatherContentObjects"
$AllShares = $null
}
return $AllShares
}
Function Convert-UNCPath {
<#
.SYNOPSIS
Prefix the path the user gives us with \\?\ to avoid the 260 MAX_PATH limit
More info https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file#maximum-path-length-limitation
#>
Param(
[string[]]$Path
)
ForEach ($item in $Path) {
switch -regex ($item) {
"^\\\\[a-zA-Z0-9`~!@#$%^&(){}\'._-]+\\[a-zA-Z0-9\\`~!@#$%^&(){}\'._ -]+" {
# Matches if it's a UNC path
# Could have queried .IsUnc property on [System.Uri] object but I wanted to verify user hadn't first given us \\?\ path type
$item -replace "^\\\\", "\\?\UNC\"
break
}
"^[a-zA-Z]:\\" {
# Matches if starts with drive letter
"\\?\" + $item
break
}
default {
$Message = "Couldn't determine path type for `"{0}`" so might have problems accessing folders that breach MAX_PATH limit, quitting..." -f $item
Write-CMLogEntry -Value $Message -Severity 2 -Component "GatherFolders"
throw $Message
}
}
}
}
Function Get-AllFolders {
<#
.SYNOPSIS
Recrusively get all folders under $Path.
.DESCRIPTION
Get all folders in $Path. By default this function escapes the max path limit by prefixing $Path with the following: "\\?\UNC". This is what _mostly_ the driver for the PoSH 5.1 requirement.
Called by main body.
.OUTPUTS
System.Object.Generic.List[String] of folder full names.
#>
Param(
[string]$Path,
[string[]]$ExcludeFolders,
[bool]$UseAltFolderSearch
)
$Path = Convert-UNCPath -Path $Path
$ExcludeFolders = Convert-UNCPath -Path $ExcludeFolders | ForEach-Object {
[Regex]::Escape($_)
}
# Recursively get all folders
if ($UseAltFolderSearch -eq $true -or $PSBoundParameters.ContainsKey("ExcludeFolders")) {
# The function handles if $ExcludeFolders is null
# Performance is better when using this style of folder recursion with exclusions / filtering right with Where-Object
[System.Collections.Generic.List[String]]$Folders = Get-AllFoldersAlt -FolderName $Path -ExcludeFolders $ExcludeFolders
}
else {
try {
[System.Collections.Generic.List[String]]$Folders = Get-ChildItem -LiteralPath $Path -Directory -Recurse -ErrorVariable GetChildItemErr | Select-Object -ExpandProperty FullName
}
catch {
$Message = "Consider using -AltFolderSearch ({0}), quiting..." -f $GetChildItemErr.Message
Write-CMLogEntry -Value $Message -Severity 3 -Component "GatherFolders"
throw $Message
}
}
# Add root directory
if ($Folders -is [System.Collections.Generic.List[String]] -And $Folders.count -gt 0) {
$Folders.Add($Path)
}
else {
$Folders = $Path
}
# Undo the \\?\ prefix
switch ($true) {
($Path -match "^\\\\\?\\UNC\\") {
# Matches if starts with \\?\UNC\
$Folders = $Folders -replace [Regex]::Escape("\\?\UNC\"), "\\"
break
}
($Path -match "^\\\\\?\\[a-zA-Z]{1}:\\") {
# Matches if starts with \\?\A:\ (A is just an example drive letter used)
$Folders = $Folders -replace [Regex]::Escape("\\?\"), ""
break
}
default {
# For some reason, couldn't undo \\?\ prefix. If you get this, please share $Path with me!
# No big deal though, can keep going. $SourcesLocation will stay as what the user gave in the parent scope
Write-CMLogEntry -Value ("Couldn't reset {0}" -f $Path) -Severity 3 -Component "GatherFolders"
}
}
$Folders | Sort-Object
}
Function Get-AllFoldersAlt {
<#
.SYNOPSIS
Get all folders under $FolderName, but not recursively.
.DESCRIPTION
Get all folders under $FolderName but does not recursively get all folders for each and every child funder.
This exists because in some environments Get-ChildItem would throw an exception "Not enough quota is available to process this command.". FullyQualifiedErrorId: "DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand".
While investigating the exception was thrown at around the 50k size of any collection type and packet traces showed SMBv1 packets returning similar exception message as by PoSH, some sort of quota limit.
Further testing on different storage systems using SMBv1 this exception was not reproducable.
Massive thanks to Chris Kibble for coming up with this work around and time to help troubleshoot!
Called by Get-AllFolders.
#>
Param(
[string]$FolderName,
[string[]]$ExcludeFolders
)
if ($null -eq $ExcludeFolders) {
$Folders = Get-ChildItem -LiteralPath $FolderName -Directory | Select-Object -ExpandProperty FullName | Where-Object {
-not [String]::IsNullOrEmpty($_)
}
}
else {
$Folders = Get-ChildItem -LiteralPath $FolderName -Directory | Select-Object -ExpandProperty FullName | Where-Object {
-not [String]::IsNullOrEmpty($_) -And $_ -notmatch [String]::Join("|", $ExcludeFolders)
}
}
ForEach ($Folder in $Folders) {
Get-AllFoldersAlt -FolderName $Folder -ExcludeFolders $ExcludeFolders
}
return $Folders
}
Function Test-FileSystemAccess {
<#
.SYNOPSIS
Check for file system access on a given folder.
.OUTPUTS
[System.Enum]
ERROR_SUCCESS (0)
ERROR_PATH_NOT_FOUND (3)
ERROR_ACCESS_DENIED (5)
ERROR_ELEVATION_REQUIRED (740)
.NOTES
Authors: Patrick Seymour / Adam Cook
Contact: @pseymour / @codaamok
#>
param
(
[Parameter(Mandatory=$false)]
[string]$Path,
[Parameter(Mandatory=$true)]
[System.Security.AccessControl.FileSystemRights]$Rights
)
enum FileSystemAccessState {
ERROR_SUCCESS
ERROR_PATH_NOT_FOUND = 3
ERROR_ACCESS_DENIED = 5
ERROR_ELEVATION_REQUIRED = 740
}
[System.Security.Principal.WindowsIdentity]$currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
[System.Security.Principal.WindowsPrincipal]$currentPrincipal = New-Object Security.Principal.WindowsPrincipal($currentIdentity)
$IsElevated = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$IsInAdministratorsGroup = $currentIdentity.Claims.Value -contains "S-1-5-32-544"
if ([System.IO.Directory]::Exists($Path))
{
try
{
[System.Security.AccessControl.FileSystemSecurity]$security = (Get-Item -Path ("FileSystem::{0}" -f $Path) -Force).GetAccessControl()
if ($null -ne $security)
{
[System.Security.AccessControl.AuthorizationRuleCollection]$rules = $security.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
for([int]$i = 0; $i -lt $rules.Count; $i++)
{
if (($currentIdentity.Groups.Contains($rules[$i].IdentityReference)) -or ($currentIdentity.User -eq $rules[$i].IdentityReference))
{
[System.Security.AccessControl.FileSystemAccessRule]$fileSystemRule = [System.Security.AccessControl.FileSystemAccessRule]$rules[$i]
if ($fileSystemRule.FileSystemRights.HasFlag($Rights))
{
return [FileSystemAccessState]::ERROR_SUCCESS
}
}
}
if (($IsElevated -eq $false) -And ($IsInAdministratorsGroup -eq $true) -And ($rules.Where( { ($_.IdentityReference -eq "S-1-5-32-544") -And ($_.FileSystemRights.HasFlag($Rights)) } )))
{
# At this point we were able to read ACL and verify Administrators group access, likely because we were qualified by the object set as owner
return [FileSystemAccessState]::ERROR_ELEVATION_REQUIRED
}
else
{
return [FileSystemAccessState]::ERROR_ACCESS_DENIED
}
}
else
{
return [FileSystemAccessState]::ERROR_ACCESS_DENIED
}
}
catch
{
return [FileSystemAccessState]::ERROR_ACCESS_DENIED
}
}
else