forked from asjimene/CMPackager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CMPackager.ps1
1813 lines (1620 loc) · 77.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
)
DynamicParam {
$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)
$configurationFileNames = Get-ChildItem -Path "$PSScriptRoot\Recipes" | Select-Object -ExpandProperty Name
$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
if (-not (Test-Path "$ScriptRoot\CMPackager.prefs" -ErrorAction SilentlyContinue)) {
$Setup = $true
}
## Global Variables (Only load if not setup)
# Import the Prefs file
if (-not ($Setup)) {
[xml]$PackagerPrefs = Get-Content $ScriptRoot\CMPackager.prefs
# Packager Vars
$Global:TempDir = $PackagerPrefs.PackagerPrefs.TempDir
$Global:LogPath = $PackagerPrefs.PackagerPrefs.LogPath
$Global:MaxLogSize = 1000kb
# Package Location Vars
$Global:ContentLocationRoot = $PackagerPrefs.PackagerPrefs.ContentLocationRoot
$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)
# 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 - $(Get-Date -format d)"
$Global:EmailBody = "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 "$PSScriptRoot\CMPackager.prefs" -ErrorAction SilentlyContinue) {
$CMPackagerXML = [XML](Get-Content "$PSScriptRoot\CMPackager.prefs")
}
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 Invoke-VersionCheck {
## Contact CM and determine if the Application Version is New
[CmdletBinding()]
param (
[Parameter()]
[String]
$ApplciationName,
[Parameter()]
[String]
$ApplciationSWVersion
)
Push-Location
Set-Location $Global:CMSite
If ((-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
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
## 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 -ApplciationName $ApplicationName -ApplciationSWVersion ([string]$ApplicationSWVersion)
}
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'
$request = Invoke-WebRequest -Uri "$URL" -OutFile $DownloadFile -ErrorAction Ignore
$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 -ApplciationName $ApplicationName -ApplciationSWVersion $ApplicationSWVersion
## Create the Application folders and copy the download if the Application is New
If ($newapp) {
## Create Application Share Folder
If ([String]::IsNullOrEmpty($AppRepoFolder)) {
$DestinationPath = "$Global:ContentLocationRoot\$ApplicationName\Packages\$Version"
Add-LogContent "Destination Path set as $DestinationPath"
}
Else {
$DestinationPath = "$Global:ContentLocationRoot\$ApplicationName\Packages\$Version\$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
$ApplicationDocURL = $Recipe.ApplicationDef.Application.UserDocumentation
$ApplicationIcon = "$Global:IconRepo\$($Recipe.ApplicationDef.Application.Icon)"
$ApplicationFolderPath = $Recipe.ApplicationDef.Application.FolderPath
if (-not (Test-Path $ApplicationIcon -ErrorAction SilentlyContinue)) {
$ApplicationIcon = "$ScriptRoot\ExtraFiles\Icons\$($Recipe.ApplicationDef.Application.Icon)"
if (-not (Test-Path $ApplicationIcon -ErrorAction SilentlyContinue)) {
$ApplicationIcon = $null
}
}
$ApplicationAutoInstall = [System.Convert]::ToBoolean($Recipe.ApplicationDef.Application.AutoInstall)
$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
if ($Global:NoVersionInSWCenter) {
$ApplicationDisplayName = "$ApplicationName"
}
else {
$ApplicationDisplayName = "$ApplicationName $ApplicationSWVersion"
}
Try {
If (-not ([System.String]::IsNullOrEmpty($ApplicationIcon))) {
Add-LogContent "Command: New-CMApplication -Name $ApplicationName $ApplicationSWVersion -Description $ApplicationDescription -Publisher $ApplicationPublisher -SoftwareVersion $ApplicationSWVersion -OptionalReference $ApplicationDocURL -AutoInstall $ApplicationAutoInstall -ReleaseDate (Get-Date) -LocalizedName $ApplicationDisplayName -LocalizedDescription $ApplicationDescription -UserDocumentation $ApplicationDocURL -IconLocationFile $ApplicationIcon"
New-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -Description "$ApplicationDescription" -Publisher "$ApplicationPublisher" -SoftwareVersion $ApplicationSWVersion -OptionalReference $ApplicationDocURL -AutoInstall $ApplicationAutoInstall -ReleaseDate (Get-Date) -LocalizedName "$ApplicationDisplayName" -LocalizedDescription "$ApplicationDescription" -UserDocumentation $ApplicationDocURL -IconLocationFile "$ApplicationIcon"
}
Else {
Add-LogContent "Command: New-CMApplication -Name $ApplicationName $ApplicationSWVersion -Description $ApplicationDescription -Publisher $ApplicationPublisher -SoftwareVersion $ApplicationSWVersion -OptionalReference $ApplicationDocURL -AutoInstall $ApplicationAutoInstall -ReleaseDate (Get-Date) -LocalizedName $ApplicationDisplayName -LocalizedDescription $ApplicationDescription -UserDocumentation $ApplicationDocURL"
New-CMApplication -Name "$ApplicationName $ApplicationSWVersion" -Description "$ApplicationDescription" -Publisher "$ApplicationPublisher" -SoftwareVersion $ApplicationSWVersion -OptionalReference $ApplicationDocURL -AutoInstall $ApplicationAutoInstall -ReleaseDate (Get-Date) -LocalizedName "$ApplicationDisplayName" -LocalizedDescription "$ApplicationDescription" -UserDocumentation $ApplicationDocURL
}
}
Catch {
$AppCreated = $false
$ErrorMessage = $_.Exception.Message
$FullyQualified = $_.FullyQualifiedErrorID
Add-LogContent "ERROR: Application Creation Failed!"
Add-LogContent "ERROR: $ErrorMessage"
Add-LogContent "ERROR: $FullyQualified"
Add-LogContent "ERROR: $($_.CategoryInfo.Category): $($_.CategoryInfo.Reason)"
}
# Move the Application to folder path if supplied
Try {
If (-not ([System.String]::IsNullOrEmpty($ApplicationFolderPath))) {
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 = $_.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))) {
$detMethodCommand += " -DirectoryName `'$($DetectionMethod.Name)`'"
}
}
File {
$detMethodCommand = "New-CMDetectionClauseFile"
If (-not ([System.String]::IsNullOrEmpty($DetectionMethod.Name))) {
$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))) {
$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))) {
$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]
}
}
switch ($ReqRuleType) {
Existential {
Add-LogContent "Existential Rule $ReqRuleVal"
$CMGlobalCondition = Get-CMGlobalCondition -Name $ReqRuleGlobalConditionName
if ([System.Convert]::ToBoolean($ReqRuleVal)) {
$rule = $CMGlobalCondition | New-CMRequirementRuleExistential -Existential $([System.Convert]::ToBoolean($($ReqRuleVal | Select-Object -first 1)))
$rule.Name = "Existential of $ReqRuleGlobalConditionName Not equal to 0"
}
else {
$rule = $CMGlobalCondition | New-CMRequirementRuleExistential -Existential $([System.Convert]::ToBoolean($($ReqRuleVal | Select-Object -first 1)))
$rule.Name = "Existential of $ReqRuleGlobalConditionName Equals 0"
}
}
OperatingSystem {
Add-LogContent "Operating System $ReqRuleOperator `"$ReqruleVal`""
# Only supporting Windows Operating Systems at this time
$GlobalCondition = Get-CMGlobalCondition -name "Operating System" | Where-Object PlatformType -eq 1
$rule = $GlobalCondition | New-CMRequirementRuleOperatingSystemValue -RuleOperator $ReqRuleOperator -PlatformStrings $ReqRuleVal
$rule.Name = "Operating System $Global:OperatorsLookup $ReqRuleValueName"
}
Default {
# DEFAULT TO VALUE
Add-LogContent "Value $ReqRuleOperator `"$ReqRuleVal`""
$CMGlobalCondition = Get-CMGlobalCondition -Name $ReqRuleGlobalConditionName
if ([System.String]::IsNullOrEmpty($ReqRuleValue2)) {
$rule = $CMGlobalCondition | New-CMRequirementRuleCommonValue -Value1 $ReqRuleVal -RuleOperator $ReqRuleOperator
$rule.Name = "$ReqRuleGlobalConditionName $Global:OperatorsLookup $ReqRuleValueName"
}
else {
$rule = $CMGlobalCondition | New-CMRequirementRuleCommonValue -Value1 $ReqRuleVal -RuleOperator $ReqRuleOperator -Value2 $ReqRuleVal2
$rule.Name = "$ReqRuleGlobalConditionName $Global:OperatorsLookup $ReqRuleValueName $ReqRuleValue2Name"
}
}
}
Add-LogContent "Adding Requirement to $ReqRuleApplicationName, $ReqRuleApplicationDTName"
Get-CMDeploymentType -ApplicationName $ReqRuleApplicationName -DeploymentTypeName $ReqRuleApplicationDTName | Set-CMDeploymentType -AddRequirement $rule
Pop-Location
}
Function Add-CMDeploymentTypeProcessDetection {
# Creates a Deployment Type Process Detection "Install Behavior tab in Deployment types".
Param (
[System.String]$DestApplicationName,
[System.String]$DestDeploymentTypeName,
[System.String]$ProcessDetectionDisplayName,
[System.String]$ProcessDetectionExecutable
)
Push-Location
Set-Location $CMSite
$DestDeploymentTypeIndex = 0
# get the applications
$DestApplication = Get-CMApplication -Name $DestApplicationName | ConvertTo-CMApplication
# Get DestDeploymentTypeIndex by finding the Title
$DestDeploymentTypeIndex = $DestApplication.DeploymentTypes.Title.IndexOf($DestDeploymentTypeName)
# Create Process Detection and set variables
$ProcessInfo = [Microsoft.ConfigurationManagement.ApplicationManagement.ProcessInformation]::new()
$ProcessInfo.DisplayInfo.Add(@{"DisplayName" = $ProcessDetectionDisplayName; Language = $NULL })
$ProcessInfo.Name = $ProcessDetectionExecutable
# push changes
$DestApplication.DeploymentTypes[$DestDeploymentTypeIndex].Installer.InstallProcessDetection.ProcessList.Add($ProcessInfo)
$CMApplication = ConvertFrom-CMApplication -Application $DestApplication
$CMApplication.Put()
Pop-Location
}
Function New-CMDeploymentTypeProcessRequirement {
# Creates a Deployment Type Process Requirement "Install Behavior tab in Deployment types" by copying an existing Process Requirement.
# LEGACY
Param (
[System.String]$SourceApplicationName,
[System.String]$DestApplicationName,
[System.String]$DestDeploymentTypeName,
[System.String]$ProcessDetectionDisplayName,
[System.String]$ProcessDetectionExecutable
)
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)
# Get requirement rules from source application
$ProcessRequirementsList = $SourceApplication.DeploymentTypes[0].Installer.InstallProcessDetection.ProcessList[0]
$ProcessRequirementsList
if (-not ([System.String]::IsNullOrEmpty($ProcessRequirementsList))) {
$ProcessRequirementsList.Name = $ProcessDetectionExecutable
$ProcessRequirementsList.DisplayInfo[0].DisplayName = $ProcessDetectionDisplayName
$ProcessRequirementsList
$DestApplication.DeploymentTypes[$DestDeploymentTypeIndex].Installer.InstallProcessDetection.ProcessList.Add($ProcessRequirementsList)
}
# push changes
$CMApplication = ConvertFrom-CMApplication -Application $DestApplication
$CMApplication.Put()
Pop-Location
}
Function Add-DeploymentType {
Param (
$Recipe
)
$ApplicationName = $Recipe.ApplicationDef.Application.Name
$ApplicationPublisher = $Recipe.ApplicationDef.Application.Publisher
$ApplicationDescription = $Recipe.ApplicationDef.Application.Description
$ApplicationDocURL = $Recipe.ApplicationDef.Application.UserDocumentation
## Set Return Value to True, It will toggle to False if something Fails
$DepTypeReturn = $true
## Loop through each Deployment Type and Add them to the Application as needed
ForEach ($DeploymentType In $Recipe.ApplicationDef.DeploymentTypes.ChildNodes) {
$DepTypeName = $DeploymentType.Name
$DepTypeDeploymentTypeName = $DeploymentType.DeploymentTypeName
Add-LogContent "New DeploymentType - $DepTypeDeploymentTypeName"
$AssociatedDownload = $Recipe.ApplicationDef.Downloads.Download | Where-Object DeploymentType -eq $DepTypeName
$ApplicationSWVersion = $AssociatedDownload.Version
$Version = $AssociatedDownload.Version
If (-not ([String]::IsNullOrEmpty($AssociatedDownload.FullVersion))) {
$FullVersion = $AssociatedDownload.FullVersion
$AppFullVersion = $AssociatedDownload.FullVersion
}
# General
$DepTypeApplicationName = "$ApplicationName $ApplicationSWVersion"
$DepTypeInstallationType = $DeploymentType.InstallationType
Add-LogContent "Deployment Type Set as: $DepTypeInstallationType"
$stDepTypeComment = $DeploymentType.Comments
$DepTypeLanguage = $DeploymentType.Language
# Content Settings
# Content Location
If ([String]::IsNullOrEmpty($AssociatedDownload.AppRepoFolder)) {
$DepTypeContentLocation = "$Global:ContentLocationRoot\$ApplicationName\Packages\$Version"
}
Else {
$DepTypeContentLocation = "$Global:ContentLocationRoot\$ApplicationName\Packages\$Version\$($AssociatedDownload.AppRepoFolder)"
}
$swDepTypeCacheContent = [System.Convert]::ToBoolean($DeploymentType.CacheContent)
$swDepTypeEnableBranchCache = [System.Convert]::ToBoolean($DeploymentType.BranchCache)
$swDepTypeContentFallback = [System.Convert]::ToBoolean($DeploymentType.ContentFallback)
$stDepTypeSlowNetworkDeploymentMode = $DeploymentType.OnSlowNetwork
# Programs
if (-not ([System.String]::IsNullOrEmpty($DeploymentType.InstallProgram))) {
$DepTypeInstallationProgram = ($DeploymentType.InstallProgram).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
}
if (-not ([System.String]::IsNullOrEmpty($DeploymentType.UninstallCmd))) {
$stDepTypeUninstallationProgram = $DeploymentType.UninstallCmd
$stDepTypeUninstallationProgram = ($stDepTypeUninstallationProgram).replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
}
$swDepTypeForce32Bit = [System.Convert]::ToBoolean($DeploymentType.Force32bit)
# User Experience
$stDepTypeInstallationBehaviorType = $DeploymentType.InstallationBehaviorType
$stDepTypeLogonRequirementType = $DeploymentType.LogonReqType
$stDepTypeUserInteractionMode = $DeploymentType.UserInteractionMode
$swDepTypeRequireUserInteraction = [System.Convert]::ToBoolean($DeploymentType.ReqUserInteraction)
$stDepTypeEstimatedRuntimeMins = $DeploymentType.EstRuntimeMins
$stDepTypeMaximumRuntimeMins = $DeploymentType.MaxRuntimeMins
$stDepTypeRebootBehavior = $DeploymentType.RebootBehavior
# Because I hate the yellow squiggly lines
Write-Output $ApplicationPublisher, $ApplicationDescription, $ApplicationDocURL, $DepTypeLanguage, $stDepTypeComment, $swDepTypeCacheContent, $swDepTypeEnableBranchCache, $swDepTypeContentFallback, $stDepTypeSlowNetworkDeploymentMode, $swDepTypeForce32Bit, $stDepTypeInstallationBehaviorType, $stDepTypeLogonRequirementType, $stDepTypeUserInteractionMode$swDepTypeRequireUserInteraction, $stDepTypeEstimatedRuntimeMins, $stDepTypeMaximumRuntimeMins, $stDepTypeRebootBehavior | Out-Null
$DepTypeDetectionMethodType = $DeploymentType.DetectionMethodType
Add-LogContent "Detection Method Type Set as $DepTypeDetectionMethodType"
$DepTypeAddDetectionMethods = $false
If (($DepTypeDetectionMethodType -eq "Custom") -and (-not ([System.String]::IsNullOrEmpty($DeploymentType.CustomDetectionMethods.ChildNodes)))) {
$DepTypeDetectionMethods = @()
$DepTypeAddDetectionMethods = $true
$DepTypeDetectionClauseConnector = @()
Add-LogContent "Adding Detection Method Clauses"
ForEach ($DetectionMethod In $($DeploymentType.CustomDetectionMethods.ChildNodes | Where-Object Name -NE "DetectionClauseExpression")) {
Add-LogContent "New Detection Method Clause $Version $FullVersion"
$DepTypeDetectionMethods += Add-DetectionMethodClause -DetectionMethod $DetectionMethod -AppVersion $Version -AppFullVersion $FullVersion
}
if (-not [System.string]::IsNullOrEmpty($($DeploymentType.CustomDetectionMethods.ChildNodes | Where-Object Name -EQ "DetectionClauseExpression"))) {
$CustomDetectionMethodExpression = ($DeploymentType.CustomDetectionMethods.ChildNodes | Where-Object Name -EQ "DetectionClauseExpression").ChildNodes
}
ForEach ($DetectionMethodExpression In $CustomDetectionMethodExpression) {
if ($DetectionMethodExpression.Name -eq "DetectionClauseConnector") {
Add-LogContent "New Detection Clause Connector $($DetectionMethodExpression.ConnectorClause),$($DetectionMethodExpression.ConnectorClauseConnector)"
$DepTypeDetectionClauseConnector += @{"LogicalName" = $DepTypeDetectionMethods[$DetectionMethodExpression.ConnectorClause].Setting.LogicalName; "Connector" = "$($DetectionMethodExpression.ConnectorClauseConnector)" }
}
if ($DetectionMethodExpression.Name -eq "DetectionClauseGrouping") {
Add-LogContent "New Detection Clause Grouping Statement Found - NOT READY YET"
}
}
}
Switch ($DepTypeInstallationType) {
Script {
Write-Host "Script Deployment"
$DepTypeCommand = "Add-CMScriptDeploymentType -ApplicationName `"$DepTypeApplicationName`" -ContentLocation `"$DepTypeContentLocation`" -DeploymentTypeName `"$DepTypeDeploymentTypeName`""
$CmdSwitches = ""
## Build the Rest of the command based on values in the xml
## Switch type Arguments
ForEach ($DepTypeVar In $(Get-Variable | Where-Object {
$_.Name -like "swDepType*"
})) {
If (([System.Convert]::ToBoolean($deptypevar.Value)) -and (-not ([System.String]::IsNullOrEmpty($DepTypeVar.Value)))) {
$CmdSwitch = "-$($($DepTypeVar.Name).Replace("swDepType", ''))"
$CmdSwitches += " $CmdSwitch"
}
}
## String Type Arguments
ForEach ($DepTypeVar In $(Get-Variable | Where-Object {
$_.Name -like "stDepType*"
})) {
If (-not ([System.String]::IsNullOrEmpty($DepTypeVar.Value))) {
$CmdSwitch = "-$($($DepTypeVar.Name).Replace("stDepType", '')) `"$($DepTypeVar.Value)`""
$CmdSwitches += " $CmdSwitch"
}
}
## Script Install Type Specific Arguments
$CmdSwitches += " -InstallCommand `'$DepTypeInstallationProgram`'"
If ($DepTypeDetectionMethodType -eq "CustomScript") {
$DepTypeScriptLanguage = $DeploymentType.ScriptLanguage
If (-not ([string]::IsNullOrEmpty($DepTypeScriptLanguage))) {
$CMDSwitch = "-ScriptLanguage `"$DepTypeScriptLanguage`""
$CmdSwitches += " $CmdSwitch"
}
$DepTypeScriptText = ($DeploymentType.DetectionMethod).Replace('$Version', $Version).replace('$FullVersion', $AppFullVersion)
If (-not ([string]::IsNullOrEmpty($DepTypeScriptText))) {
$CMDSwitch = "-ScriptText `'$DepTypeScriptText`'"
$CmdSwitches += " $CmdSwitch"
}
}
$DepTypeForce32BitDetection = $DeploymentType.ScriptDetection32Bit
If (([System.Convert]::ToBoolean($DepTypeForce32BitDetection)) -and (-not ([System.String]::IsNullOrEmpty($DepTypeForce32BitDetection)))) {
$CmdSwitches += " -ForceScriptDetection32Bit"
}
## Run the Add-CMApplicationDeployment Command
$DeploymentTypeCommand = "$DepTypeCommand$CmdSwitches"
If ($DepTypeAddDetectionMethods) {
$DeploymentTypeCommand += " -ScriptType Powershell -ScriptText `"write-output 0`""
}