-
Notifications
You must be signed in to change notification settings - Fork 68
/
CMPackager.ps1
2173 lines (1936 loc) · 92.7 KB
/
CMPackager.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
<#
.NOTES
===========================================================================
Created on: 1/9/2018 11:34 AM
Last Updated: 05/06/2020
Author: Andrew Jimenez (asjimene) - https://github.com/asjimene/
Filename: CMPackager.ps1
===========================================================================
.DESCRIPTION
Packages Applications for ConfigMgr using XML Based Recipe Files
Uses Scripts and Functions Sourced from the Following:
Copy-CMDeploymentTypeRule - https://janikvonrotz.ch/2017/10/20/configuration-manager-configure-requirement-rules-for-deployment-types-with-powershell/
Get-ExtensionAttribute - Jaap Brasser - http://www.jaapbrasser.com
Get-MSIInfo - Nickolaj Andersen - http://www.scconfigmgr.com/2014/08/22/how-to-get-msi-file-information-with-powershell/
7-Zip Application is Redistributed for Ease of Use:
7-Zip Binary - Igor Pavlov - https://www.7-zip.org/
#>
[CmdletBinding()]
param (
[switch]$Setup = $false,
[ValidateScript({
if (-not ($_ | Resolve-Path | Test-Path -PathType Leaf)) {
throw "File doesn't exist or a file wasn't specified."
}
return $true
})]
[System.IO.FileInfo]$PreferenceFile = "$PSScriptRoot\CMPackager.prefs",
[ValidateScript({
if (-not ($_ | Resolve-Path | Test-Path -PathType Container)) {
throw "Directory doesn't exist or a directory wasn't specified."
}
return $true
})]
[System.IO.DirectoryInfo]$RecipePath = "$PSScriptRoot\Recipes"
)
DynamicParam {
# If RecipePath is specified populate list of available recipes from custom recipe location
if ($PSBoundParameters['RecipePath']) {
$configurationFileNames = Get-ChildItem *.xml -Path $($PSBoundParameters['RecipePath']) | Select-Object -ExpandProperty Name
}
else
{
# If RecipePath is note specified, check to see if running from the CMPackager directory and populate from standard recipe directory
if ((test-path .\Recipes) -and (test-path .\cmpackager.ps1)) {
$configurationFileNames = Get-ChildItem *.xml -Path .\Recipes | Select-Object -ExpandProperty Name
}
}
# Make SingleRecipe parameter availabe only if possible recipes are found in the above checked custom or standard dirs
if ($configurationFileNames) {
$ParamAttrib = New-Object System.Management.Automation.ParameterAttribute
$ParamAttrib.Mandatory = $false
$ParamAttrib.ParameterSetName = '__AllParameterSets'
$AttribColl = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$AttribColl.Add($ParamAttrib)
$AttribColl.Add((New-Object System.Management.Automation.AliasAttribute('Recipe')))
$AttribColl.Add((New-Object System.Management.Automation.ValidateSetAttribute($configurationFileNames)))
$RuntimeParam = New-Object System.Management.Automation.RuntimeDefinedParameter('SingleRecipe', [string[]], $AttribColl)
$RuntimeParamDic = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$RuntimeParamDic.Add('SingleRecipe', $RuntimeParam)
return $RuntimeParamDic
}
}
process {
$Global:ScriptVersion = "20.05.06.0"
$Global:ScriptRoot = $PSScriptRoot
Write-Host "Preference file: $($PreferenceFile), Recipe path: $($RecipePath)"
if (-not (Test-Path $PreferenceFile -ErrorAction SilentlyContinue)) {
$Setup = $true
}
## Global Variables (Only load if not setup)
# Import the Prefs file
if (-not ($Setup)) {
[xml]$PackagerPrefs = Get-Content $PreferenceFile
# Packager Vars
$Global:TempDir = $PackagerPrefs.PackagerPrefs.TempDir
$Global:LogPath = $PackagerPrefs.PackagerPrefs.LogPath
$Global:MaxLogSize = 1000kb
# Package Location Vars
$Global:ContentLocationRoot = $PackagerPrefs.PackagerPrefs.ContentLocationRoot
$Global:ContentFolderPattern = $PackagerPrefs.PackagerPrefs.ContentFolderPattern
$Global:IconRepo = $PackagerPrefs.PackagerPrefs.IconRepo
# CM Vars
$Global:CMSite = $PackagerPrefs.PackagerPrefs.CMSite
$Global:SiteCode = ($Global:CMSite).Replace(':', '')
$Global:SiteServer = $PackagerPrefs.PackagerPrefs.SiteServer
$Global:RequirementsTemplateAppName = $PackagerPrefs.PackagerPrefs.RequirementsTemplateAppName
$Global:PreferredDistributionLoc = $PackagerPrefs.PackagerPrefs.PreferredDistributionLoc
$Global:PreferredDeployCollection = $PackagerPrefs.PackagerPrefs.PreferredDeployCollection
$Global:NoVersionInSWCenter = [System.Convert]::ToBoolean($PackagerPrefs.PackagerPrefs.NoVersionInSWCenter)
$Global:CMPSModulePath = $PackagerPrefs.PackagerPrefs.CMPSModulePath
# Email Vars
[string[]]$Global:EmailTo = [string[]]$PackagerPrefs.PackagerPrefs.EmailTo
$Global:EmailFrom = $PackagerPrefs.PackagerPrefs.EmailFrom
$Global:EmailServer = $PackagerPrefs.PackagerPrefs.EmailServer
$Global:SendEmailPreference = [System.Convert]::ToBoolean($PackagerPrefs.PackagerPrefs.SendEmailPreference)
$Global:NotifyOnDownloadFailure = [System.Convert]::ToBoolean($PackagerPrefs.PackagerPrefs.NotifyOnDownloadFailure)
$Global:EmailSubject = "CMPackager Report [$Global:CMSite] - $(Get-Date -format d)"
$Global:EmailBody = "[$Global:CMSite] New Application Updates Packaged on $(Get-Date -Format d)`n`n"
#This gets switched to True if Applications are Packaged
$Global:SendEmail = $false
$Global:TemplateApplicationCreatedFlag = $false
}
$Global:ConfigMgrConnection = $false
$Global:XMLtoDisplayHash = @{"TempDir" = "WPFtextBoxWorkingDir";
"ContentLocationRoot" = "WPFtextBoxContentRoot";
"IconRepo" = "WPFtextBoxIconRepository";
"CMSite" = "WPFtextBoxSiteCode";
"SiteServer" = "WPFtextBoxSiteServer";
"NoVersionInSWCenter" = "WPFtoggleButtonNoDisplayAppVer";
"EmailTo" = "WPFtextBoxEmailTo";
"EmailFrom" = "WPFtextBoxEmailFrom";
"EmailServer" = "WPFtextBoxEmailServer";
"SendEmailPreference" = "WPFtoggleButtonSendEmail";
"NotifyOnDownloadFailure" = "WPFtoggleButtonNotifyOnFailure";
"PreferredDistributionLoc" = "WPFcomboBoxPreferredDistPoint";
"PreferredDeployCollection" = "WPFcomboBoxPreferredDeployColl"
}
if (Test-Path $PreferenceFile -ErrorAction SilentlyContinue) {
$CMPackagerXML = [XML](Get-Content $PreferenceFile)
}
else {
$CMPackagerXML = [XML](Get-Content "$PSScriptRoot\CMPackager.prefs.template")
}
$Global:OperatorsLookup = @{ And = 'And'; Or = 'Or'; Other = 'Other'; IsEquals = 'Equals'; NotEquals = 'Not equal to'; GreaterThan = 'Greater than'; LessThan = 'Less than'; Between = 'Between'; NotBetween = 'Not Between'; GreaterEquals = 'Greater than or equal to'; LessEquals = 'Less than or equal to'; BeginsWith = 'Begins with'; NotBeginsWith = 'Does not begin with'; EndsWith = 'Ends with'; NotEndsWith = 'Does not end with'; Contains = 'Contains'; NotContains = 'Does not contain'; AllOf = 'All of'; OneOf = 'OneOf'; NoneOf = 'NoneOf'; SetEquals = 'Set equals'; SubsetOf = 'Subset of'; ExcludesAll = 'Exludes all' }
## Functions
function Add-LogContent {
param
(
[parameter(Mandatory = $false)]
[switch]$Load,
[parameter(Mandatory = $true)]
$Content
)
if ($Load) {
if ((Get-Item $LogPath -ErrorAction SilentlyContinue).length -gt $MaxLogSize) {
Write-Output "$(Get-Date -Format G) - $Content" > $LogPath
}
else {
Write-Output "$(Get-Date -Format G) - $Content" >> $LogPath
}
}
else {
Write-Output "$(Get-Date -Format G) - $Content" >> $LogPath
}
}
function Get-ExtensionAttribute {
<#
.Synopsis
Retrieves extension attributes from files or folder
.DESCRIPTION
Uses the dynamically generated parameter -ExtensionAttribute to select one or multiple extension attributes and display the attribute(s) along with the FullName attribute
.NOTES
Name: Get-ExtensionAttribute.ps1
Author: Jaap Brasser
Version: 1.0
DateCreated: 2015-03-30
DateUpdated: 2015-03-30
Blog: http://www.jaapbrasser.com
.LINK
http://www.jaapbrasser.com
.PARAMETER FullName
The path to the file or folder of which the attributes should be retrieved. Can take input from pipeline and multiple values are accepted.
.PARAMETER ExtensionAttribute
Additional values to be loaded from the registry. Can contain a string or an array of string that will be attempted to retrieve from the registry for each program entry
.EXAMPLE
. .\Get-ExtensionAttribute.ps1
Description
-----------
This command dot sources the script to ensure the Get-ExtensionAttribute function is available in your current PowerShell session
.EXAMPLE
Get-ExtensionAttribute -FullName C:\Music -ExtensionAttribute Size,Length,Bitrate
Description
-----------
Retrieves the Size,Length,Bitrate and FullName of the contents of the C:\Music folder, non recursively
.EXAMPLE
Get-ExtensionAttribute -FullName C:\Music\Song2.mp3,C:\Music\Song.mp3 -ExtensionAttribute Size,Length,Bitrate
Description
-----------
Retrieves the Size,Length,Bitrate and FullName of Song.mp3 and Song2.mp3 in the C:\Music folder
.EXAMPLE
Get-ChildItem -Recurse C:\Video | Get-ExtensionAttribute -ExtensionAttribute Size,Length,Bitrate,Totalbitrate
Description
-----------
Uses the Get-ChildItem cmdlet to provide input to the Get-ExtensionAttribute function and retrieves selected attributes for the C:\Videos folder recursively
.EXAMPLE
Get-ChildItem -Recurse C:\Music | Select-Object FullName,Length,@{Name = 'Bitrate' ; Expression = { Get-ExtensionAttribute -FullName $_.FullName -ExtensionAttribute Bitrate | Select-Object -ExpandProperty Bitrate } }
Description
-----------
Combines the output from Get-ChildItem with the Get-ExtensionAttribute function, selecting the FullName and Length properties from Get-ChildItem with the ExtensionAttribute Bitrate
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
Position = 0)]
[string[]]$FullName
)
DynamicParam {
$Attributes = New-Object System.Management.Automation.ParameterAttribute
$Attributes.ParameterSetName = "__AllParameterSets"
$Attributes.Mandatory = $false
$AttributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$AttributeCollection.Add($Attributes)
$Values = @($Com = (New-Object -ComObject Shell.Application).NameSpace('C:\'); 1 .. 400 | ForEach-Object { $com.GetDetailsOf($com.Items, $_) } | Where-Object { $_ } | ForEach-Object { $_ -replace '\s' })
$AttributeValues = New-Object System.Management.Automation.ValidateSetAttribute($Values)
$AttributeCollection.Add($AttributeValues)
$DynParam1 = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ExtensionAttribute", [string[]], $AttributeCollection)
$ParamDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$ParamDictionary.Add("ExtensionAttribute", $DynParam1)
$ParamDictionary
}
begin {
$ShellObject = New-Object -ComObject Shell.Application
$DefaultName = $ShellObject.NameSpace('C:\')
$ExtList = 0 .. 400 | ForEach-Object {
($DefaultName.GetDetailsOf($DefaultName.Items, $_)).ToUpper().Replace(' ', '')
}
}
process {
foreach ($Object in $FullName) {
# Check if there is a fullname attribute, in case pipeline from Get-ChildItem is used
if ($Object.FullName) {
$Object = $Object.FullName
}
# Check if the path is a single file or a folder
if (-not (Test-Path -Path $Object -PathType Container)) {
$CurrentNameSpace = $ShellObject.NameSpace($(Split-Path -Path $Object))
$CurrentNameSpace.Items() | Where-Object {
$_.Path -eq $Object
} | ForEach-Object {
$HashProperties = @{
FullName = $_.Path
}
foreach ($Attribute in $MyInvocation.BoundParameters.ExtensionAttribute) {
$HashProperties.$($Attribute) = $CurrentNameSpace.GetDetailsOf($_, $($ExtList.IndexOf($Attribute.ToUpper())))
}
New-Object -TypeName PSCustomObject -Property $HashProperties
}
}
elseif (-not $input) {
$CurrentNameSpace = $ShellObject.NameSpace($Object)
$CurrentNameSpace.Items() | ForEach-Object {
$HashProperties = @{
FullName = $_.Path
}
foreach ($Attribute in $MyInvocation.BoundParameters.ExtensionAttribute) {
$HashProperties.$($Attribute) = $CurrentNameSpace.GetDetailsOf($_, $($ExtList.IndexOf($Attribute.ToUpper())))
}
New-Object -TypeName PSCustomObject -Property $HashProperties
}
}
}
}
end {
Remove-Variable -Force -Name DefaultName
Remove-Variable -Force -Name CurrentNameSpace
Remove-Variable -Force -Name ShellObject
}
}
function Get-MSIInfo {
param (
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.IO.FileInfo]$Path,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet("ProductCode", "ProductVersion", "ProductName", "Manufacturer", "ProductLanguage", "FullVersion", "InstallPrerequisites")]
[string]$Property
)
Process {
try {
# Read property from MSI database
$WindowsInstaller = New-Object -ComObject WindowsInstaller.Installer
$MSIDatabase = $WindowsInstaller.GetType().InvokeMember("OpenDatabase", "InvokeMethod", $null, $WindowsInstaller, @($Path.FullName, 0))
$Query = "SELECT Value FROM Property WHERE Property = '$($Property)'"
$View = $MSIDatabase.GetType().InvokeMember("OpenView", "InvokeMethod", $null, $MSIDatabase, ($Query))
$View.GetType().InvokeMember("Execute", "InvokeMethod", $null, $View, $null)
$Record = $View.GetType().InvokeMember("Fetch", "InvokeMethod", $null, $View, $null)
$Value = $Record.GetType().InvokeMember("StringData", "GetProperty", $null, $Record, 1)
# Commit database and close view
$MSIDatabase.GetType().InvokeMember("Commit", "InvokeMethod", $null, $MSIDatabase, $null)
$View.GetType().InvokeMember("Close", "InvokeMethod", $null, $View, $null)
$MSIDatabase = $null
$View = $null
# Return the value
return $Value
}
catch {
Write-Warning -Message $_.Exception.Message; break
}
}
End {
# Run garbage collection and release ComObject
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WindowsInstaller) | Out-Null
[System.GC]::Collect()
}
}
function Get-MSISourceFileVersion {
<#
.SYNOPSIS
Get the version of a file from an MSI's File Table
.DESCRIPTION
Search a Windows Installer database's File Table for a file name and return the version.
.EXAMPLE
PS C:\> Get-MSISourceFileVersion -Msi "C:\Program Files\Microsoft Configuration Manager\tools\ConsoleSetup\AdminConsole.msi" -FileName 'ConBlder.exe|AdminUI.ConsoleBuilder.exe'
Get the version of the file 'ConBlder.exe|AdminUI.ConsoleBuilder.exe'
.NOTES
https://docs.microsoft.com/en-us/windows/win32/msi/file-table
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)][ValidateScript({Test-Path $_})][Alias('Installer')]
$Msi, # The MSI to query
[Parameter(Mandatory)][ValidateNotNullOrEmpty()]
$FileName # The file to find the version of. Must be an exact match, in the Windows Installer's format including the shortname https://docs.microsoft.com/en-us/windows/win32/msi/filename.
)
begin {
$windowsInstaller = New-Object -ComObject WindowsInstaller.Installer
}
process {
try {
$database = $windowsInstaller.GetType().InvokeMember(
"OpenDatabase", "InvokeMethod", $null,
$windowsInstaller, @((Get-Item $Msi).FullName, 0)
)
$query = "SELECT FileName,Version FROM File WHERE FileName = '$filename'"
$view = $database.GetType().InvokeMember(
"OpenView", "InvokeMethod", $null, $database, $query
)
$view.GetType().InvokeMember("Execute", "InvokeMethod", $null, $view, $null) | Out-Null
$record = $view.GetType().InvokeMember(
"Fetch", "InvokeMethod", $null, $view, $null
)
while ($record -ne $null) {
$fileName = $record.GetType().InvokeMember("StringData", "GetProperty", $null, $record, 1)
$version = $record.GetType().InvokeMember("StringData", "GetProperty", $null, $record, 2)
Write-Output ([version]$version)
$record = $view.GetType().InvokeMember("Fetch", "InvokeMethod", $null, $view, $null)
}
} finally {
$view.GetType().InvokeMember("Close", "InvokeMethod", $null, $view, $null) | Out-Null
}
}
} # Get-MSISourceFileVersion
function Invoke-VersionCheck {
## Contact CM and determine if the Application Version is New
[CmdletBinding()]
param (
[Parameter()]
[String]
$ApplicationName,
[Parameter()]
[String]
$ApplicationSWVersion,
[Parameter()]
[Switch]
# Require versions that can be parsed as a version or int to be higher than currently in CM as well as not previously added
$RequireHigherVersion
)
Push-Location
Set-Location $Global:CMSite
If ($RequireHigherVersion -and ($ApplicationSWVersion -as [version])) {
# Use [version] for proper sorting
Add-LogContent "Requiring new version numbers to be higher than current"
$currentHighest = Get-CMApplication -Name "$ApplicationName*" |
Select-Object -ExpandProperty SoftwareVersion -ErrorAction SilentlyContinue |
ForEach-Object {$_ -as [version]} |
Sort-Object -Descending |
Select-Object -First 1
$newApp = ($ApplicationSWVersion -as [version]) -gt $currentHighest
if ($newApp) {Add-LogContent "$ApplicationSWVersion is a new and higher version"}
else {Add-LogContent "$ApplicationSWVersion is not new and higher - Moving to next application"}
}
ElseIf ($RequireHigherVersion -and ($ApplicationSWVersion -as [int])) {
# Try [int]
Add-LogContent "Requiring new version numbers to be higher than current"
$currentHighest = Get-CMApplication -Name "$ApplicationName*" |
Select-Object -ExpandProperty SoftwareVersion -ErrorAction SilentlyContinue |
ForEach-Object {$_ -as [int]} |
Sort-Object -Descending |
Select-Object -First 1
$newApp = ($ApplicationSWVersion -as [int]) -gt $currentHighest
if ($newApp) {Add-LogContent "$ApplicationSWVersion is a new and higher version"}
else {Add-LogContent "$ApplicationSWVersion is not new and higher - Moving to next application"}
}
ElseIf ((-not (Get-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -Fast)) -and (-not ([System.String]::IsNullOrEmpty($ApplicationSWVersion)))) {
$newApp = $true
Add-LogContent "$ApplicationSWVersion is a new Version"
}
Else {
$newApp = $false
Add-LogContent "$ApplicationSWVersion is not a new Version - Moving to next application"
}
# If SkipPackaging is specified, return that the app is up-to-date.
if ($ApplicationSWVersion -eq "SkipPackaging") {
$newApp = $false
}
Pop-Location
Write-Output $newApp
}
Function Start-ApplicationDownload {
Param (
$Recipe
)
$ApplicationName = $Recipe.ApplicationDef.Application.Name
$ApplicationPublisher = $Recipe.ApplicationDef.Application.Publisher
ForEach ($Download In $Recipe.ApplicationDef.Downloads.ChildNodes) {
## Set Variables
$newApp = $false
$DownloadFileName = $Download.DownloadFileName
$URL = $Download.URL
$DownloadVersionCheck = $Download.DownloadVersionCheck
$DownloadFile = "$TempDir\$DownloadFileName"
$AppRepoFolder = $Download.AppRepoFolder
$ExtraCopyFunctions = $Download.ExtraCopyFunctions
$RequireHigherVersion = [System.Convert]::ToBoolean($Download.RequireHigherVersion)
## Run the prefetch script if it exists, the prefetch script can be used to determine the location of the download URL, and optionally provide
## the software version before the download occurs
$PrefetchScript = $Download.PrefetchScript
If (-not ([String]::IsNullOrEmpty($PrefetchScript))) {
Invoke-Expression $PrefetchScript | Out-Null
}
if (-not ([System.String]::IsNullOrEmpty($Download.Version))) {
## Version Check after prefetch script (skip download if possible)
## To Set the Download Version in the Prefetch Script, Simply set the variable $Download.Version to the [String]Version of the Application
$ApplicationSWVersion = $Download.Version
Add-LogContent "Prefetch Script Provided a Download Version of: $ApplicationSWVersion"
$newApp = Invoke-VersionCheck -ApplicationName $ApplicationName -ApplicationSWVersion ([string]$ApplicationSWVersion) -RequireHigherVersion:$RequireHigherVersion
}
else {
$newApp = $true
}
Add-LogContent "Version Check after prefetch script is $newapp"
if ($newApp) {
Add-LogContent "$ApplicationName will be downloaded"
}
else {
Add-LogContent "$ApplicationName will not be downloaded"
}
## Download the Application
If ((-not ([String]::IsNullOrEmpty($URL))) -and ($newapp)) {
Add-LogContent "Downloading $ApplicationName from $URL"
$ProgressPreference = 'SilentlyContinue'
IF ($HTTPheaders) {
$request = Invoke-WebRequest -Uri "$URL" -OutFile $DownloadFile -Headers $HTTPheaders
}
else {
$request = Invoke-WebRequest -Uri "$URL" -OutFile $DownloadFile
}
$request | Out-Null
Add-LogContent "Completed Downloading $ApplicationName"
## Run the Version Check Script and record the Version and FullVersion
If (-not ([String]::IsNullOrEmpty($DownloadVersionCheck))) {
Invoke-Expression $DownloadVersionCheck | Out-Null
$Download.Version = [string]$Version
$Download.FullVersion = [string]$FullVersion
}
$ApplicationSWVersion = $Download.Version
Add-LogContent "Found Version $ApplicationSWVersion from Download FullVersion: $FullVersion"
}
else {
if (-not $newApp) {
Add-LogContent "$Version was found in ConfigMgr, Skipping Download"
}
if ([String]::IsNullOrEmpty($URL)) {
Add-LogContent "URL Not Specified, Skipping Download"
}
}
## Determine if the Download Failed or if an Application Version was not detected, and add the Failure to the email if the Flag is set
if (((-not (Test-Path $DownloadFile)) -and $newApp) -or ([System.String]::IsNullOrEmpty($ApplicationSWVersion))) {
Add-LogContent "ERROR: Failed to Download or find the Version for $ApplicationName"
if ($Global:NotifyOnDownloadFailure) {
$Global:SendEmail = $true; $Global:SendEmail | Out-Null
$Global:EmailBody += " - Failed to Download: $ApplicationName`n"
}
}
$newApp = Invoke-VersionCheck -ApplicationName $ApplicationName -ApplicationSWVersion $ApplicationSWVersion -RequireHigherVersion:$RequireHigherVersion
## Create the Application folders and copy the download if the Application is New
If ($newapp) {
## Create Application Share Folder
$ContentPath = "$Global:ContentLocationRoot\$ApplicationName\Packages\$Version"
if ($Global:ContentFolderPattern) {
$ContentFolderPatternReplace = $Global:ContentFolderPattern -Replace '\$ApplicationName',$ApplicationName -Replace '\$Publisher',$ApplicationPublisher -Replace '\$Version',$Version
$ContentPath = "$Global:ContentLocationRoot\$ContentFolderPatternReplace"
}
If ([String]::IsNullOrEmpty($AppRepoFolder)) {
$DestinationPath = $ContentPath
Add-LogContent "Destination Path set as $DestinationPath"
}
Else {
$DestinationPath = "$ContentPath\$AppRepoFolder"
Add-LogContent "Destination Path set as $DestinationPath"
}
New-Item -ItemType Directory -Path $DestinationPath -Force
## Copy to Download to Application Share
Add-LogContent "Copying downloads to $DestinationPath"
Copy-Item -Path $DownloadFile -Destination $DestinationPath -Force
## Extra Copy Functions If Required
If (-not ([String]::IsNullOrEmpty($ExtraCopyFunctions))) {
Add-LogContent "Performing Extra Copy Functions"
Invoke-Expression $ExtraCopyFunctions | Out-Null
}
}
}
## Return True if All Downloaded Applications were new Versions
Return $NewApp
}
Function Invoke-ApplicationCreation {
Param (
$Recipe
)
## Set Variables
$ApplicationName = $Recipe.ApplicationDef.Application.Name
$ApplicationPublisher = $Recipe.ApplicationDef.Application.Publisher
$ApplicationDescription = $Recipe.ApplicationDef.Application.Description
$ApplicationAdminDescription = $Recipe.ApplicationDef.Application.AdminDescription
$ApplicationDocURL = $Recipe.ApplicationDef.Application.UserDocumentation
$ApplicationOptionalReference = $Recipe.ApplicationDef.Application.OptionalReference
$ApplicationLinkText = $Recipe.ApplicationDef.Application.LinkText
$ApplicationPrivacyUrl = $Recipe.ApplicationDef.Application.PrivacyUrl
$ApplicationFolderPath = $Recipe.ApplicationDef.Application.FolderPath
$ApplicationOwner = $Recipe.ApplicationDef.Application.Owner
$ApplicationSupportContact = $Recipe.ApplicationDef.Application.SupportContact
$ApplicationKeywords = $Recipe.ApplicationDef.Application.Keywords
$ApplicationUserCategories = $Recipe.ApplicationDef.Application.UserCategories
$ApplicationAdminCategories = $Recipe.ApplicationDef.Application.AdminCategories
$ApplicationIcon = $Recipe.ApplicationDef.Application.Icon
$LocalizedName = $Recipe.ApplicationDef.Application.LocalizedName
$ApplicationAutoInstall = [System.Convert]::ToBoolean($Recipe.ApplicationDef.Application.AutoInstall)
$ApplicationDisplaySupersedence = [System.Convert]::ToBoolean($Recipe.ApplicationDef.Application.DisplaySupersedence)
$ApplicationIsFeatured = [System.Convert]::ToBoolean($Recipe.ApplicationDef.Application.FeaturedApplication)
$AppCreated = $true
ForEach ($Download In ($Recipe.ApplicationDef.Downloads.Download)) {
If (-not ([System.String]::IsNullOrEmpty($Download.Version))) {
$ApplicationSWVersion = $Download.Version
}
}
## Create the Application
Push-Location
Set-Location $Global:CMSite
Add-LogContent "Creating Application: $ApplicationName $ApplicationSWVersion"
# Change the SW Center Display Name based on Setting
$ApplicationDisplayName = if ($LocalizedName) {$LocalizedName} else {$ApplicationName}
if (!$Global:NoVersionInSWCenter) { $ApplicationDisplayName += " $ApplicationSWVersion"}
Add-LogContent "Building application import command"
# Because I (also) hate the yellow squiggly lines
Write-Output $ApplicationDisplayName, $ApplicationPublisher, $ApplicationAutoInstall, $ApplicationDisplaySupersedence, $ApplicationIsFeatured | Out-Null
# Reference: https://docs.microsoft.com/en-us/powershell/module/configurationmanager/new-cmapplication
$NewAppCommand = 'New-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -LocalizedName "$ApplicationDisplayName" -SoftwareVersion "$ApplicationSWVersion" -ReleaseDate $(Get-Date) -AutoInstall $ApplicationAutoInstall -DisplaySupersedenceInApplicationCatalog $ApplicationDisplaySupersedence -IsFeatured $ApplicationIsFeatured'
$CmdSwitches = ''
## Build the rest of the command based on values in the xml
If (-not ([System.String]::IsNullOrEmpty($ApplicationPublisher))) {
$CmdSwitches += ' -Publisher "$ApplicationPublisher"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationDescription))) {
$CmdSwitches += ' -LocalizedDescription "$ApplicationDescription"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationIcon))) {
if (Test-Path "$Global:IconRepo\$ApplicationIcon") {
$CmdSwitches += " -IconLocationFile ""$Global:IconRepo\$ApplicationIcon"""
} elseif (Test-Path "$ScriptRoot\ExtraFiles\Icons\$ApplicationIcon") {
$CmdSwitches += " -IconLocationFile ""$ScriptRoot\ExtraFiles\Icons\$ApplicationIcon"""
} else {
Add-LogContent "ERROR: Unable to find icon $ApplicationIcon, creating application without icon"
}
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationDocURL))) {
$CmdSwitches += ' -UserDocumentation "$ApplicationDocURL"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationOptionalReference))) {
$CmdSwitches += ' -OptionalReference "$ApplicationOptionalReference"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationAdminDescription))) {
$CmdSwitches += ' -Description "$ApplicationAdminDescription"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationOwner))) {
$CmdSwitches += ' -Owner "$ApplicationOwner"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationSupportContact))) {
$CmdSwitches += ' -SupportContact "$ApplicationSupportContact"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationKeywords))) {
$CmdSwitches += ' -Keyword "$ApplicationKeywords"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationLinkText))) {
$CmdSwitches += ' -LinkText "$ApplicationLinkText"'
}
If (-not ([System.String]::IsNullOrEmpty($ApplicationPrivacyUrl))) {
$CmdSwitches += ' -PrivacyUrl "$ApplicationPrivacyUrl"'
}
## Run the New-CMApplication Command
$NewAppCommandFull = "$NewAppCommand$CmdSwitches"
Add-LogContent "Command: $NewAppCommandFull"
Try {
Invoke-Expression $NewAppCommandFull | Out-Null
Add-LogContent "Application Created"
}
Catch {
$AppCreated = $false
$ErrorMessage = $_.Exception.Message
$FullyQualified = $_.Exeption.FullyQualifiedErrorID
Add-LogContent "ERROR: Creating Application Failed!"
Add-LogContent "ERROR: $ErrorMessage"
Add-LogContent "ERROR: $FullyQualified"
Add-LogContent "ERROR: $($_.CategoryInfo.Category): $($_.CategoryInfo.Reason)"
}
# Apply categories if supplied. This was not availabe during application creation
if ($AppCreated) {
Try {
## Set user categories that display in Software Center
If (-not ([System.String]::IsNullOrEmpty($ApplicationUserCategories))) {
## Create list to store user categories
$AppUserCatList = New-Object System.Collections.ArrayList
foreach ($ApplicationUserCategory in ($ApplicationUserCategories).Split(",")) {
if (-not (($AppUserCatObj = Get-CMCategory -Name $ApplicationUserCategory | Where-Object {$_.CategoryTypeName -eq "CatalogCategories"}))) {
## Create if not found and add to list
Add-LogContent "$ApplicationUserCategory category was supplied in recipe, but does not exist. Creating user category"
$null = $AppUserCatList.Add((New-CMCategory -CategoryType "CatalogCategories" -Name $ApplicationUserCategory))
} else {
## Add to list
$null = $AppUserCatList.Add($AppUserCatObj)
}
}
}
## Set administrative categories that display in admin console
If (-not ([System.String]::IsNullOrEmpty($ApplicationAdminCategories))) {
## Create list to store admin categories
$AppAdminCatList = New-Object System.Collections.ArrayList
foreach ($ApplicationAdminCategory in ($ApplicationAdminCategories).Split(",")) {
if (-not (($AppAdminCatObj = Get-CMCategory -Name $ApplicationAdminCategory | Where-Object {$_.CategoryTypeName -eq "AppCategories"}))) {
## Create if not found and add to list
Add-LogContent "$ApplicationAdminCategory category was supplied in recipe, but does not exist. Creating admin category"
$null = $AppAdminCatList.Add((New-CMCategory -CategoryType "AppCategories" -Name $ApplicationAdminCategory))
} else {
## Add to list
$null = $AppAdminCatList.Add($AppAdminCatObj)
}
}
}
## Run Set-CMApplication depending on which types of categories exist
## Reference: https://docs.microsoft.com/en-us/powershell/module/configurationmanager/set-cmapplication
if (($AppUserCatList) -and ($AppAdminCatList)) {
Set-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -AddAppCategory $AppAdminCatList -AddUserCategory $AppUserCatList
} elseif ($AppUserCatList) {
Set-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -AddUserCategory $AppUserCatList
} elseif ($AppAdminCatList) {
Set-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -AddAppCategory $AppAdminCatList
}
}
Catch {
$AppCreated = $false
$ErrorMessage = $_.Exception.Message
$FullyQualified = $_.Exception.FullyQualifiedErrorID
Add-LogContent "ERROR: Setting Application Categories Failed!"
Add-LogContent "ERROR: $ErrorMessage"
Add-LogContent "ERROR: $FullyQualified"
Add-LogContent "ERROR: $($_.CategoryInfo.Category): $($_.CategoryInfo.Reason)"
}
}
# Move the Application to folder path if supplied
If ($AppCreated) {
Try {
If (-not ([System.String]::IsNullOrEmpty($ApplicationFolderPath))) {
# Create the folder if it does not exist
if (-not (Test-Path ".\Application\$ApplicationFolderPath")) {
New-Item -ItemType Directory -Path ".\Application\$ApplicationFolderPath" -ErrorAction SilentlyContinue
}
Add-LogContent "Command: Move-CMObject -InputObject (Get-CMApplication -Name ""$ApplicationName $ApplicationSWVersion"") -FolderPath "".\Application\$ApplicationFolderPath"""
Move-CMObject -InputObject (Get-CMApplication -Name "$ApplicationName $ApplicationSWVersion") -FolderPath ".\Application\$ApplicationFolderPath"
}
}
Catch {
$AppCreated = $false
$ErrorMessage = $_.Exception.Message
$FullyQualified = $_.Exception.FullyQualifiedErrorID
Add-LogContent "ERROR: Application Move Failed!"
Add-LogContent "ERROR: $ErrorMessage"
Add-LogContent "ERROR: $FullyQualified"
Add-LogContent "ERROR: $($_.CategoryInfo.Category): $($_.CategoryInfo.Reason)"
}
}
## Send an Email if an Application was successfully Created and record the Application Name and Version for the Email
If ($AppCreated) {
$Global:SendEmail = $true; $Global:SendEmail | Out-Null
$Global:EmailBody += " - $ApplicationName $ApplicationSWVersion`n"
}
Pop-Location
## Return True if the Application was Created Successfully
Return $AppCreated
}
Function Add-DetectionMethodClause {
Param (
$DetectionMethod,
$AppVersion,
$AppFullVersion
)
$detMethodDetectionClauseType = $DetectionMethod.DetectionClauseType
Add-LogContent "Adding Detection Method Clause Type $detMethodDetectionClauseType"
Switch ($detMethodDetectionClauseType) {
Directory {
$detMethodCommand = "New-CMDetectionClauseDirectory"
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Name))) {
$DetectionMethod.Name = ($DetectionMethod.Name).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
$detMethodCommand += " -DirectoryName `'$($DetectionMethod.Name)`'"
}
}
File {
$detMethodCommand = "New-CMDetectionClauseFile"
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Name))) {
$DetectionMethod.Name = ($DetectionMethod.Name).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
$detMethodCommand += " -FileName `'$($DetectionMethod.Name)`'"
}
}
RegistryKey {
$detMethodCommand = "New-CMDetectionClauseRegistryKey"
}
RegistryKeyValue {
$detMethodCommand = "New-CMDetectionClauseRegistryKeyValue"
}
WindowsInstaller {
$detMethodCommand = "New-CMDetectionClauseWindowsInstaller"
}
}
If (([System.Convert]::ToBoolean($DetectionMethod.Existence)) -and (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Existence)))) {
$detMethodCommand += " -Existence"
}
If (([System.Convert]::ToBoolean($DetectionMethod.Is64Bit)) -and (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Is64Bit)))) {
$detMethodCommand += " -Is64Bit"
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Path))) {
$DetectionMethod.Path = ($DetectionMethod.Path).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
$detMethodCommand += " -Path `'$($DetectionMethod.Path)`'"
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.PropertyType))) {
$detMethodCommand += " -PropertyType $($DetectionMethod.PropertyType)"
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.ExpectedValue))) {
$DetectionMethod.ExpectedValue = ($DetectionMethod.ExpectedValue).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
$detMethodCommand += " -ExpectedValue `"$($DetectionMethod.ExpectedValue)`""
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.ExpressionOperator))) {
$detMethodCommand += " -ExpressionOperator $($DetectionMethod.ExpressionOperator)"
}
If (([System.Convert]::ToBoolean($DetectionMethod.Value)) -and (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Value)))) {
$detMethodCommand += " -Value"
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Hive))) {
$detMethodCommand += " -Hive $($DetectionMethod.Hive)"
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.KeyName))) {
$DetectionMethod.KeyName = ($DetectionMethod.KeyName).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
$detMethodCommand += " -KeyName `"$($DetectionMethod.KeyName)`""
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.ValueName))) {
$detMethodCommand += " -ValueName `"$($DetectionMethod.ValueName)`""
}
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.ProductCode))) {
$detMethodCommand += " -ProductCode `"$($DetectionMethod.ProductCode)`""
}
Add-LogContent "$detMethodCommand"
## Run the Detection Method Command as Created by the Logic Above
Push-Location
Set-Location $CMSite
Try {
$DepTypeDetectionMethod += Invoke-Expression $detMethodCommand
}
Catch {
$ErrorMessage = $_.Exception.Message
$FullyQualified = $_.Exeption.FullyQualifiedErrorID
Add-LogContent "ERROR: Creating Detection Method Clause Failed!"
Add-LogContent "ERROR: $ErrorMessage"
Add-LogContent "ERROR: $FullyQualified"
}
Pop-Location
## Return the Detection Method Variable
Return $DepTypeDetectionMethod
}
Function Copy-CMDeploymentTypeRule {
<#
Function taken from https://janikvonrotz.ch/2017/10/20/configuration-manager-configure-requirement-rules-for-deployment-types-with-powershell/ and modified
#>
Param (
[System.String]$SourceApplicationName,
[System.String]$DestApplicationName,
[System.String]$DestDeploymentTypeName,
[System.String]$RuleName
)
Push-Location
Set-Location $CMSite
$DestDeploymentTypeIndex = 0
# get the applications
$SourceApplication = Get-CMApplication -Name $SourceApplicationName | ConvertTo-CMApplication
$DestApplication = Get-CMApplication -Name $DestApplicationName | ConvertTo-CMApplication
# Get DestDeploymentTypeIndex by finding the Title
$DestDeploymentTypeIndex = $DestApplication.DeploymentTypes.Title.IndexOf($DestDeploymentTypeName)
$Available = ($SourceApplication.DeploymentTypes[0].Requirements).Name
Add-LogContent "Available Requirements to chose from:`r`n $($Available -Join ', ')"
# get requirement rules from source application
$Requirements = $SourceApplication.DeploymentTypes[0].Requirements | Where-Object { (($_.Name).TrimStart().TrimEnd()) -eq (($RuleName).TrimStart().TrimEnd()) }
if ([System.String]::IsNullOrEmpty($Requirements)) {
Add-LogContent "No Requirement rule was an exact match for $RuleName"
$Requirements = $SourceApplication.DeploymentTypes[0].Requirements | Where-Object { $_.Name -match $RuleName }
}
if ([System.String]::IsNullOrEmpty($Requirements)) {
Add-LogContent "No Requirement rule was matched, tring one more thing for $RuleName"
$Requirements = $SourceApplication.DeploymentTypes[0].Requirements | Where-Object { $_.Name -like $RuleName }
}
Add-LogContent "$($Requirements.Name) will be added"
# apply requirement rules
$Requirements | ForEach-Object {
$RuleExists = $DestApplication.DeploymentTypes[$DestDeploymentTypeIndex].Requirements | Where-Object { $_.Name -match $RuleName }
if ($RuleExists) {
Add-LogContent "WARN: The rule `"$($_.Name)`" already exists in target application deployment type"
}
else {
Add-LogContent "Apply rule `"$($_.Name)`" on target application deployment type"
# create new rule ID
$_.RuleID = "Rule_$( [guid]::NewGuid())"
$DestApplication.DeploymentTypes[$DestDeploymentTypeIndex].Requirements.Add($_)
}
}
# push changes
$CMApplication = ConvertFrom-CMApplication -Application $DestApplication
$CMApplication.Put()
Pop-Location
}
function Add-RequirementsRule {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateSet('Value', 'Existential', 'OperatingSystem')]
[String]
$ReqRuleType,
[Parameter()]
[ValidateSet( 'And', 'Or', 'Other', 'IsEquals', 'NotEquals', 'GreaterThan', 'LessThan', 'Between', 'NotBetween', 'GreaterEquals', 'LessEquals', 'BeginsWith', 'NotBeginsWith', 'EndsWith', 'NotEndsWith', 'Contains', 'NotContains', 'AllOf', 'OneOf', 'NoneOf', 'SetEquals', 'SubsetOf', 'ExcludesAll')]
$ReqRuleOperator,
[Parameter(Mandatory)]
[String[]]
$ReqRuleValue,
[Parameter()]
[String[]]
$ReqRuleValue2,
[Parameter()]
[String]
$ReqRuleGlobalConditionName,
[Parameter(Mandatory)]
[String]
$ReqRuleApplicationName,
[Parameter(Mandatory)]
[String]
$ReqRuleApplicationDTName
)
Push-Location
Set-Location $Global:CMSite
Write-Host "`"$ReqRuleType of $ReqRuleGlobalConditionName $ReqRuleOperator $ReqRuleValue`" is being added"
if (-not ([System.String]::IsNullOrEmpty($ReqRuleValue))) {
$ReqRuleValueName = $ReqRuleValue
#if (($ReqRuleOperator -eq 'Oneof') -or ($ReqRuleOperator -eq 'Noneof') -or ($ReqRuleOperator -eq 'Allof') -or ($ReqRuleOperator -eq 'Subsetof') -or ($ReqRuleOperator -eq 'ExcludesAll')) {
if ($ReqRuleValue[1]) {
$ReqRuleVal = $ReqRuleValue
$ReqRuleValueName = "{ $($ReqRuleVal -join ", ") }"
}
if ([system.string]::IsNullOrEmpty($ReqRuleVal)) {
$ReqRuleVal = $ReqRuleValue[0]
}
}
if (-not ([System.String]::IsNullOrEmpty($ReqRuleValue2))) {
if ($ReqRuleValue2[1]) {
$ReqRuleVal2 = $ReqRuleValue2
$ReqRuleValue2Name = "{ $($ReqRuleVal2 -join ", ") }"
}
if ([system.string]::IsNullOrEmpty($ReqRuleVal)) {
$ReqRuleVal2 = $ReqRuleValue2[0]
}
}