-
Notifications
You must be signed in to change notification settings - Fork 106
/
PowerSCCM.ps1
5932 lines (4341 loc) · 193 KB
/
PowerSCCM.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
#requires -version 2
# global store for established Sccm connection objects
[System.Collections.ArrayList]$Script:SccmSessions = @()
$Script:SccmSessionCounter = 0
# make sure sessions are killed on powershell.exe exit
$Null = Register-EngineEvent -SourceIdentifier ([Management.Automation.PsEngineEvent]::Exiting) -Action {
Write-Warning 'Cleaning up any existing Sccm connections!'
Get-SccmSession | Remove-SccmSession
}
function New-SccmSession {
<#
.SYNOPSIS
Initiates a new Sccm database connection, returning a custom PowerSccm.Session
object that stores a unique Id and Name, as well as permission and connection
information. Also stores the PowerSccm.Session object in the $Script:SccmSessions
array for later access by Get-SccmSession.
.PARAMETER ComputerName
The hostname of the Sccm database server.
.PARAMETER SiteCode
The three letter site code of the Sccm distribution site. Discoverable with Find-SccmSiteCode.
.PARAMETER ConnectionType
The method to connect to the remote Sccm server. 'WMI' uses a WMI connection and the
Sccm SMS_ WMI classes. 'Database'/'DB'/'SQL' connects to the Sccm MSSQL backend database.
Default to WMI.
.PARAMETER Credential
A [Management.Automation.PSCredential] object that stores a SqlUserName and SqlPassword
or a domain credential to use for WMI connections.
.PARAMETER SqlUserName
Specific MSSQL username to use instead of integrated Windows authentication.
.PARAMETER SqlPassword
Specific MSSQL username to use instead of integrated Windows authentication.
.EXAMPLE
PS C:\> New-SccmSession -ComputerName SccmServer -SiteCode LOL -ConnectionType WMI
Connect to the LOL sitecode namespace on SccmServer over WMI.
.EXAMPLE
PS C:\> New-SccmSession -ComputerName SccmServer -SiteCode LOL -ConnectionType Database
Connect to the CM_LOL MSSQL database on SccmServer.
.EXAMPLE
PS C:\> New-SccmSession -ComputerName Sccm -SiteCode LOL -SqlUserName sqladmin -SqlPassword 'Password123!'
Connect to the CM_LOL database on SccmServer using explicit MSSQL credentials
and store the connection object.
#>
[CmdletBinding(DefaultParameterSetName = 'None')]
param(
[Parameter(Position = 0, Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$ComputerName,
[Parameter(Position = 1, Mandatory = $True)]
[String]
[ValidatePattern('^[A-Za-z0-9]{3}$')]
$SiteCode,
[Parameter(Position = 2, Mandatory = $True)]
[String]
[ValidateSet("Database", "DB", "SQL", "WMI")]
$ConnectionType,
[Parameter(Position = 3)]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential = [Management.Automation.PSCredential]::Empty,
[Parameter(ParameterSetName = 'SQLCredentials', Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$SqlUserName,
[Parameter(ParameterSetName = 'SQLCredentials', Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$SqlPassword
)
if(($ConnectionType -notlike "WMI") -or $PSBoundParameters['SqlUserName']) {
# if we're connecting to the Sccm MSSQL database
try {
$DatabaseName = "CM_$SiteCode"
Write-Verbose "Connecting to Sccm server\database $ComputerName\$DatabaseName"
$SQLConnection = New-Object System.Data.SQLClient.SQLConnection
if($PSBoundParameters['Credential']) {
$SqlUserName = $Credential.UserName
$SqlPassword = $Credential.GetNetworkCredential().Password
Write-Verbose "Connecting using MSSQL credentials: '$SqlUserName : $SqlPassword'"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;User Id=$SqlUserName;Password=$SqlPassword;Trusted_Connection=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
elseif($PSBoundParameters['SqlUserName']) {
Write-Verbose "Connecting using MSSQL credentials: '$SqlUserName : $SqlPassword'"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;User Id=$SqlUserName;Password=$SqlPassword;Trusted_Connection=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
else {
Write-Verbose "Connecting using integrated Windows authentication"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;Integrated Security=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
$SQLConnection.Open()
$Script:SccmSessionCounter += 1
$SccmSessionObject = New-Object PSObject
$SccmSessionObject | Add-Member Noteproperty 'Id' $Script:SccmSessionCounter
$SccmSessionObject | Add-Member Noteproperty 'Name' $($SiteCode + $Script:SccmSessionCounter)
$SccmSessionObject | Add-Member Noteproperty 'ComputerName' $ComputerName
$SccmSessionObject | Add-Member Noteproperty 'Credential' $Null
$SccmSessionObject | Add-Member Noteproperty 'SiteCode' $SiteCode
$SccmSessionObject | Add-Member Noteproperty 'ConnectionType' $ConnectionType
$SccmSessionObject | Add-Member Noteproperty 'SccmVersion' $Null
$SccmSessionObject | Add-Member Noteproperty 'Permissions' $Null
$SccmSessionObject | Add-Member Noteproperty 'Provider' $SQLConnection
# add in our custom object type
$SccmSessionObject.PSObject.TypeNames.Add('PowerSccm.Session')
# get the Sccm version used
$SccmVersionQuery = "SELECT TOP 1 LEFT(Client_Version0,CHARINDEX('.',Client_Version0)-1) as Sccm_Version FROM v_R_System"
$SccmVersion = (Invoke-SccmQuery -Session $SccmSessionObject -Query $SccmVersionQuery).Sccm_Version
$SccmSessionObject.SccmVersion = $SccmVersion
# get the current user database permissions
$PermissionsQuery = "SELECT permission_name FROM fn_my_permissions (NULL, 'DATABASE')"
$Permissions = Invoke-SccmQuery -Session $SccmSessionObject -Query $PermissionsQuery | ForEach-Object { $_.permission_name }
$SccmSessionObject.Permissions = $Permissions
if(!($Permissions -contains "SELECT")) {
Write-Warning "Current user does not have SELECT permissions!"
}
if(!($Permissions -contains "UPDATE")) {
Write-Warning "Current user does not have UPDATE permissions!"
}
}
catch {
Write-Error "[!] Error connecting to $ComputerName\$DatabaseName : $_"
}
}
else {
Write-Verbose "Connecting to Sccm server\site $ComputerName\$SiteCode via WMI"
try {
$Script:SccmSessionCounter += 1
$SccmSessionObject = New-Object PSObject
$SccmSessionObject | Add-Member Noteproperty 'Id' $Script:SccmSessionCounter
$SccmSessionObject | Add-Member Noteproperty 'Name' $($SiteCode + $Script:SccmSessionCounter)
$SccmSessionObject | Add-Member Noteproperty 'ComputerName' $ComputerName
$Query = "SELECT * FROM SMS_ProviderLocation where SiteCode = '$SiteCode'"
if($PSBoundParameters['Credential']) {
$SccmProvider = Get-WmiObject -ComputerName $ComputerName -Query $Query -Namespace "root\sms" -Credential $Credential
$SccmSessionObject | Add-Member Noteproperty 'Credential' $Credential
}
else {
$SccmProvider = Get-WmiObject -ComputerName $ComputerName -Query $Query -Namespace "root\sms"
$SccmSessionObject | Add-Member Noteproperty 'Credential' $Null
}
$SccmSessionObject | Add-Member Noteproperty 'SiteCode' $SiteCode
$SccmSessionObject | Add-Member Noteproperty 'ConnectionType' $ConnectionType
$SccmSessionObject | Add-Member Noteproperty 'SccmVersion' $Null
$SccmSessionObject | Add-Member Noteproperty 'Permissions' @("ALL")
$SccmSessionObject | Add-Member Noteproperty 'Provider' $SccmProvider
# add in our custom object type
$SccmSessionObject.PSObject.TypeNames.Add('PowerSccm.Session')
$SccmVersion = (Invoke-SccmQuery -Session $SccmSessionObject -Query "SELECT * FROM SMS_R_System" | Select-Object -First 1 -Property ClientVersion).ClientVersion.Split(".")[0]
$SccmSessionObject.SccmVersion = $SccmVersion
}
catch {
Write-Error "[!] Error connecting to $ComputerName\$WMISiteCode via WMI : $_"
}
}
if($SccmSessionObject) {
# return the new session object to the pipeline
$SccmSessionObject
# store the session object in the script store
$Null = $Script:SccmSessions.add($SccmSessionObject)
}
}
function Get-SccmSession {
<#
.SYNOPSIS
Returns a specified stored PowerSccm.Session object or all
stored PowerSccm.Session objects.
.PARAMETER Id
The Id of a stored Sccm session object created by New-SccmSession.
.PARAMETER Name
The Name of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER ComputerName
The ComputerName of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER SiteCode
The SiteCode of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER ConnectionType
The ConnectionType of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.EXAMPLE
PS C:\> Get-SccmSession
Return all active Sccm sessions stored.
.EXAMPLE
PS C:\> Get-SccmSession -Id 3
Return the active sessions stored for Id of 3
.EXAMPLE
PS C:\> Get-SccmSession -Name LOL1
Return named LOL1 session.
.EXAMPLE
PS C:\> Get-SccmSession -ComputerName SccmSERVER
Return the active sessions stored for the SccmSERVER machine
.EXAMPLE
PS C:\> Get-SccmSession -SiteCode LOL
Return the active sessions stored sitcode LOL.
.EXAMPLE
PS C:\> Get-SccmSession -ConnectionType WMI
Return active WMI sessions.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$True, ValueFromPipeline=$True)]
[ValidateScript({ $_.PSObject.TypeNames -contains 'PowerSccm.Session'})]
$Session,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[Int]
$Id,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateNotNullOrEmpty()]
$Name,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateNotNullOrEmpty()]
$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidatePattern('^[A-Za-z]{3}$')]
$SiteCode,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateSet("Database", "DB", "SQL", "WMI")]
$ConnectionType
)
if($PSBoundParameters['Session']) {
$Session
}
elseif($Script:SccmSessions) {
if($PSBoundParameters['Id']) {
$Script:SccmSessions.Clone() | Where-Object {
$_.Id -eq $Id
}
}
elseif($PSBoundParameters['Name']) {
$Script:SccmSessions.Clone() | Where-Object {
$_.Name -like $Name
}
}
elseif($PSBoundParameters['ComputerName']) {
if($PSBoundParameters['SiteCode']) {
$Script:SccmSessions.Clone() | Where-Object {
($_.ComputerName -like $ComputerName) -and ($_.SiteCode -like $SiteCode)
}
}
else {
$Script:SccmSessions.Clone() | Where-Object {
$_.ComputerName -like $ComputerName
}
}
}
elseif($PSBoundParameters['SiteCode']) {
$Script:SccmSessions.Clone() | Where-Object {
$_.SiteCode -like $SiteCode
}
}
elseif($PSBoundParameters['ConnectionType']) {
$Script:SccmSessions.Clone() | Where-Object {
$_.ConnectionType -like $ConnectionType
}
}
else {
$Script:SccmSessions.Clone()
}
}
}
function Remove-SccmSession {
<#
.SYNOPSIS
Closes and destroys a Sccm database connection object either passed
on the pipeline or specified by the Id/Name/ComputerName/SiteCode/ConnectionType.
.PARAMETER Session
The custom PowerSccm.Session object generated and stored by New-SccmSession,
passable on the pipeline.
.PARAMETER Id
The Id of a stored Sccm session object created by New-SccmSession.
.PARAMETER Name
The Name of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER ComputerName
The ComputerName of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER SiteCode
The SiteCode of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.PARAMETER ConnectionType
The ConnectionType of a stored Sccm session object created by New-SccmSession,
wildcards accepted.
.EXAMPLE
PS C:\> Remove-SccmSession -Id 3
Destroy/remove the active database sessions stored for Id of 3
.EXAMPLE
PS C:\> Remove-SccmSession -Name LOL1
Destroy/remove the named LOL1 active database session
.EXAMPLE
PS C:\> Remove-SccmSession -ComputerName SccmSERVER
Destroy/remove the active database sessions stored for the SccmSERVER machine
.EXAMPLE
PS C:\> Remove-SccmSession -SiteCode LOL
Destroy/remove the active database sessions stored for sitecode of LOL.
.EXAMPLE
PS C:\> Get-SccmSession -Name LOL1 | Remove-SccmSession
Close/destroy the active database session stored for the LOL1 named session.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$True, ValueFromPipeline=$True)]
[ValidateScript({ $_.PSObject.TypeNames -contains 'PowerSccm.Session'})]
$Session,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[Int]
$Id,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateNotNullOrEmpty()]
$Name,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateNotNullOrEmpty()]
$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidatePattern('^[A-Za-z]{3}$')]
$SiteCode,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
[ValidateSet("Database", "DB", "SQL", "WMI")]
$ConnectionType
)
process {
Get-SccmSession @PSBoundParameters | ForEach-Object {
Write-Verbose "Removing session '$($_.Name)'"
if($_.ConnectionType -NotLike "WMI") {
$_.Provider.Close()
}
$Script:SccmSessions.Remove($_)
}
}
}
function Invoke-SccmQuery {
<#
.SYNOPSIS
Helper that executes a given Sccm SQL or WMI query on the passed Sccm
session object.
Should not normally be called by the user.
.PARAMETER Session
The custom PowerSccm.Session object returned by Get-SccmSession, passable on the pipeline.
.PARAMETER Query
The Sccm SQL or WMI query to run.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory = $True, ValueFromPipeline=$True)]
[ValidateScript({ $_.PSObject.TypeNames -contains 'PowerSccm.Session'})]
$Session,
[Parameter(Position = 1, Mandatory = $True)]
[String]
$Query
)
process {
if($Query.Trim().StartsWith("-- MIN_Sccm_VERSION")) {
# if the query specifies a minimum version, make sure this connection complies
$FirstLine = $($Query -Split "\n")[0]
$MinVersion = ($FirstLine -Split "=")[1].trim()
if($MinVersion) {
if($MinVersion -gt $($Session.SccmVersion)) {
Throw "Query requires a minimum Sccm version ($MinVersion) higher than the current connection ($($Session.SccmVersion))!"
}
}
}
if($Session.ConnectionType -Like "WMI") {
Write-Verbose "Running WMI query on session $($Session.Name): $Query"
$Namespace = $($Session.Provider.NamespacePath -split "\\", 4)[3]
if($Session.Credential) {
Get-WmiObject -ComputerName $Session.ComputerName -Namespace $Namespace -Query $Query -Credential $Session.Credential
}
else {
Get-WmiObject -ComputerName $Session.ComputerName -Namespace $Namespace -Query $Query
}
}
else {
Write-Verbose "Running database SQL query on session $($Session.Name): $Query"
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($Query, $Session.Provider)
$Table = New-Object System.Data.DataSet
$Null = $SqlAdapter.Fill($Table)
$Table.Tables[0]
}
}
}
function Get-SQLQueryFilter {
<#
.SYNOPSIS
Helper that takes a -Query SQL string and a set of PSBoundParameters
and returns the appropriate final query string for a Get-Sccm*
function based on the given filter options.
.PARAMETER Query
The multi-line SQL query string to append logic to.
.PARAMETER Parameters
The passed $PSBoundParameter set.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory=$True)]
[String]
[ValidateNotNullOrEmpty()]
$Query,
[Parameter(Position = 1, Mandatory=$True)]
$Parameters
)
if($Parameters['FilterRaw']) {
# if a single hard -Filter <X> is set, ignore other filter parameters
$Filter = $Filter.Replace('*', '%')
if($Query.EndsWith("AS DATA")) {
$Query += "`nWHERE ($Filter)"
}
else {
$Query += "`nAND ($Filter)"
}
}
else {
$Parameters.GetEnumerator() | Where-Object {($_.Key -like '*Filter') -and ($_.Key -ne 'Filter')} | ForEach-Object {
# get the SQL wildcards correct
$Value = $_.Value.Replace('*', '%')
# if we have multiple values to build clauses for
if($Value.Contains(" or ")){
$Values = $Value -split " or " | ForEach-Object {$_.trim()}
}
else {
$Values = @($Value)
}
if($Query.Contains("AS DATA")) {
if($Query.EndsWith("AS DATA")) {
$Query += "`nWHERE ("
}
else {
$Query += "`nAND ("
}
}
elseif($Query.Contains("WHERE")) {
$Query += "`nAND ("
}
else {
$Query += "`nWHERE ("
}
$Clauses = @()
ForEach ($Value in $Values) {
if($Value.StartsWith('!')) {
$Operator = "NOT LIKE"
$Value = $Value.Substring(1)
}
elseif($Value.StartsWith("<") -or $Value.StartsWith(">")) {
$Operator = $Value[0]
$Value = $Value.Substring(1)
}
else {
$Operator = "LIKE"
}
if($_.Key -eq "ComputerNameFilter") {
$IP = $Null
$IPAddress = [Net.IPAddress]::TryParse($Value, [Ref] $IP)
if($IPAddress) {
$Clauses += @("IPAddress $Operator '$($Value)%'")
}
else {
# otherwise we have a computer name
$Clauses += @("ComputerName $Operator '$Value'")
}
}
else {
# chop off "...Filter"
$Field = $_.Key.Substring(0,$_.Key.Length-6)
$Clauses += @("$Field $Operator '$Value'")
}
}
$Query += $Clauses -join " OR "
$Query += ")"
}
}
if($Parameters['OrderBy']) {
$Query += "`nORDER BY $OrderBy"
if($Parameters['Descending']) {
$Query += " DESC"
}
}
$Query
}
function Get-WMIQueryFilter {
<#
.SYNOPSIS
Helper that takes a -Query WMI string and a set of PSBoundParameters
and returns the appropriate final query string for a Get-Sccm*
function based on the given filter options.
.PARAMETER Query
The multi-line WMI query string to append logic to.
.PARAMETER Parameters
The passed $PSBoundParameter set.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory=$True)]
[String]
[ValidateNotNullOrEmpty()]
$Query,
[Parameter(Position = 1, Mandatory=$True)]
$Parameters
)
if($Parameters['Filter']) {
# if a single hard -Filter <X> is set, ignore other filter parameters
$Filter = $Filter.Replace('*', '%')
$Query += "`nWHERE ($Filter)"
}
else {
$Parameters.GetEnumerator() | Where-Object {($_.Key -like '*Filter') -and ($_.Key -ne 'Filter')} | ForEach-Object {
# get the WQL wildcards correct
$Value = $_.Value.Replace('*', '%')
# escape backslashes for WQL
$Value = $Value.Replace('\', '\\')
# if we have multiple values to build clauses for
if($Value.Contains(" or ")){
$Values = $Value -split " or " | ForEach-Object {$_.trim()}
}
else {
$Values = @($Value)
}
if($Query.Contains("WHERE")) {
$Query += "`nAND ("
}
else {
$Query += "`nWHERE ("
}
$Clauses = @()
ForEach ($Value in $Values) {
if($Value.StartsWith('!')) {
$Operator = "NOT LIKE"
$Value = $Value.Substring(1)
}
elseif($Value.StartsWith("<") -or $Value.StartsWith(">")) {
$Operator = $Value[0]
$Value = $Value.Substring(1)
}
else {
$Operator = "LIKE"
}
if($_.Key -eq "ComputerNameFilter") {
$IP = $Null
$IPAddress = [Net.IPAddress]::TryParse($Value, [Ref] $IP)
if($IPAddress) {
$Clauses += @("IPAddress $Operator '$($Value)%'")
}
else {
# otherwise we have a computer name
$Clauses += @("ComputerName $Operator '$Value'")
}
}
else {
# chop off "...Filter"
$Field = $_.Key.Substring(0,$_.Key.Length-6)
$Clauses += @("$Field $Operator '$Value'")
}
}
$Query += $Clauses -join " OR "
$Query += ")"
}
}
$Query
}
##############################################
#
# Functions that query or modified information
# in the Sccm database/server itself (as opposed) to
# client information in the Sccm database).
#
##############################################
function Find-LocalSccmInfo {
<#
.SYNOPSIS
Queries the local SMS_Authority Class to determine the Site Code and the Management Point
.EXAMPLE
PS C:\> Find-LocalSccmInfo
Gets the primary Management Point and Site code for the local host via the SMS_Authority WMI class.
#>
[CmdletBinding()]
param()
$SmsAuthority = Get-WmiObject -Namespace "Root\CCM" -Class "SMS_Authority"
$SMSSiteCode = $SmsAuthority.Name.Remove(0, 4)
$SMSManagementServer = $SmsAuthority.CurrentManagementPoint
New-Object PSObject -Property @{'ManagementServer' = $SMSManagementServer; 'SiteCode' = $SMSSiteCode}
}
function Find-SccmSiteCode {
<#
.SYNOPSIS
Takes a given Sccm server and returns available site names.
.PARAMETER ComputerName
The Sccm server computername to enumerate.
.PARAMETER ConnectionType
The method to connect to the remote Sccm server. 'WMI' uses a WMI connection and the
Sccm SMS_ WMI classes. 'Database'/'DB'/'SQL' connects to the Sccm MSSQL backend database.
Default to WMI.
.PARAMETER Credential
A [Management.Automation.PSCredential] object that stores a SqlUserName and SqlPassword
or a domain credential to use for WMI connections.
.PARAMETER SqlUserName
Specific MSSQL username to use instead of integrated Windows authentication.
.PARAMETER SqlPassword
Specific MSSQL username to use instead of integrated Windows authentication.
#>
[CmdletBinding(DefaultParameterSetName = 'None')]
param(
[Parameter(Position = 0, Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$ComputerName,
[Parameter(Position = 1)]
[String]
[ValidateSet("Database", "DB", "SQL", "WMI")]
$ConnectionType = "SQL",
[Parameter(Position = 2)]
[Management.Automation.PSCredential]
[Management.Automation.CredentialAttribute()]
$Credential = [Management.Automation.PSCredential]::Empty,
[Parameter(ParameterSetName = 'SQLCredentials', Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$SqlUserName,
[Parameter(ParameterSetName = 'SQLCredentials', Mandatory = $True)]
[String]
[ValidateNotNullOrEmpty()]
$SqlPassword
)
process {
if($ConnectionType -like "WMI") {
$Query = "SELECT * FROM SMS_ProviderLocation where ProviderForLocalSite = true"
if($Session.Credential) {
Get-WmiObject -ComputerName $ComputerName -Namespace "root\sms" -Query $Query -Credential $Session.Credential | ForEach-Object {New-Object PSObject -Property @{'SiteCode' = $_.SiteCode}}
}
else {
Get-WmiObject -ComputerName $ComputerName -Namespace "root\sms" -Query $Query | ForEach-Object {New-Object PSObject -Property @{'SiteCode' = $_.SiteCode}}
}
}
else {
try {
# ...yes I know this is duplicate logic MATT :)
# this seemed to be the easiest way to preserve the functionality
# of New-SccmSession without major modification
$SQLConnection = New-Object System.Data.SQLClient.SQLConnection
if($PSBoundParameters['Credential']) {
$SqlUserName = $Credential.UserName
$SqlPassword = $Credential.GetNetworkCredential().Password
Write-Verbose "Connecting using MSSQL credentials: '$SqlUserName : $SqlPassword'"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;User Id=$SqlUserName;Password=$SqlPassword;Trusted_Connection=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
elseif($PSBoundParameters['SqlUserName']) {
Write-Verbose "Connecting using MSSQL credentials: '$SqlUserName : $SqlPassword'"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;User Id=$SqlUserName;Password=$SqlPassword;Trusted_Connection=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
else {
Write-Verbose "Connecting using integrated Windows authentication"
$SQLConnection.ConnectionString ="Server=$ComputerName;Database=$DatabaseName;Integrated Security=True;"
Write-Verbose "Connection string: $($SQLConnection.ConnectionString)"
}
$SQLConnection.Open()
$Query = "SELECT name FROM Sys.Databases WHERE name LIKE 'CM_%' AND state_desc = 'ONLINE'"
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($Query, $SQLConnection)
$Table = New-Object System.Data.DataSet
$Null = $SqlAdapter.Fill($Table)
$Table.Tables[0] | ForEach-Object {
New-Object PSObject -Property @{'SiteCode' = $($_[0] -split "_")[1]}
}
$SQLConnection.Close()
}
catch {
Write-Error "Error enumerating SQL database on server '$ComputerName' : $_"
}
}
}
}
function Get-SccmApplication {
<#
.SYNOPSIS
Returns applications that exist on the primary site server.
.PARAMETER Session
The custom PowerSccm.Session object to query, generated/stored by New-SccmSession
and retrievable with Get-SccmSession. Required. Passable on the pipeline.
.PARAMETER Newest
Restrict the underlying Sccm SQL query to only return the -Newest <X> number of results.
Detaults to the max value of a 32-bit integer (2147483647).
.PARAMETER OrderBy
Order the results by a particular field.
.PARAMETER Descending
Switch. If -OrderBy <X> is specified, -Descending will sort the results by
the given field in descending order.
.PARAMETER CreatedByFilter
Query only for results where the CreatedBy field matches the given filter.
Wildcards accepted.
.PARAMETER DisplayNameFilter
Query only for results where the DisplayName field matches the given filter.
Wildcards accepted.
.PARAMETER CI_IDFilter
Query only for results where the CI_ID field matches the given filter.
Wildcards accepted.
.PARAMETER DeploymentTypeName
Query only for results where the DeploymentType field matches the given filter.
Wildcards accepted.
.PARAMETER DTInstallString
Query only for results where the DTInstallString field matches the given filter.
Wildcards accepted.
.PARAMETER DateCreatedFilter
Query only for results where the DateCreated field matches the given filter.
Wildcards accepted.
.PARAMETER LastModifiedFilter
Query only for results where the LastModified field matches the given filter.
Wildcards accepted.
.PARAMETER LastModifiedByFilter
Query only for results where the LastModifiedBy field matches the given filter.
Wildcards accepted.
.PARAMETER IsHidden
Query only for results where the IsHidden field matches the given filter.
Wildcards accepted.
.PARAMETER Filter
Raw filter to build a WHERE clause instead of -XFilter options.
Form of "ComputerName like '%WINDOWS%' OR Name like '%malicious%'"
.EXAMPLE
PS C:\> Get-SccmSession | Get-SccmApplication
Runs the query against all current Sccm sessions.
.EXAMPLE
PS C:\> Get-SccmSession | Get-SccmApplication -FilterName IsHidden -FilterValue 1