forked from SMSAgentSoftware/ConfigMgr-Task-Sequence-Monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.7_ConfigMgrTSMonitor.ps1
2112 lines (1891 loc) · 81.1 KB
/
1.7_ConfigMgrTSMonitor.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 3
$currentLocation = if($PSScriptRoot){ $PSScriptRoot } else { (Get-Location).Path }
Write-Host $currentLocation
Set-Location $currentLocation
#region Add Assemblies
Add-Type -AssemblyName PresentationFramework, System.Drawing, System.Windows.Forms, WindowsFormsIntegration
$code = @"
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System
{
public class IconExtractor
{
public static Icon Extract(string file, int number, bool largeIcon)
{
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try
{
return Icon.FromHandle(largeIcon ? large : small);
}
catch
{
return null;
}
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}
}
"@
Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing
# Mahapps Library
if (Test-Path -Path "$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\MahApps.Metro.dll")
{
[System.Reflection.Assembly]::LoadFrom("$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\MahApps.Metro.dll") | out-null
[System.Reflection.Assembly]::LoadFrom("$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\System.Windows.Interactivity.dll") | out-null
}
if (Test-Path -Path "${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\MahApps.Metro.dll")
{
[System.Reflection.Assembly]::LoadFrom("${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\MahApps.Metro.dll") | out-null
[System.Reflection.Assembly]::LoadFrom("${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\System.Windows.Interactivity.dll") | out-null
}
if (Test-Path -Path "$currentLocation\MahApps.Metro.dll")
{
[System.Reflection.Assembly]::LoadFrom("$currentLocation\MahApps.Metro.dll") | out-null
[System.Reflection.Assembly]::LoadFrom("$currentLocation\System.Windows.Interactivity.dll") | out-null
}
#endregion
#region GUI and Variables
### Main Window ###
# GUI
[xml]$xaml = Get-Content ($currentLocation + "\XAML\MainWindow.xaml")
$BuildExtVersionSql = @()
Import-Csv -Path ($currentLocation + "\BuildExt.csv") -Delimiter ";" -Header Build, Version | ForEach-Object {
$BuildExtVersionSql += "WHEN sys.BuildExt like '$($_.Build)' THEN '$($_.Version)'"
}
$hash = [hashtable]::Synchronized(@{})
$reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $xaml)
$hash.Window = [Windows.Markup.XamlReader]::Load( $reader )
$global:PSInstances = @()
$Global:Timezones = @()
$hash.TaskSequence = $hash.Window.FindName('TaskSequence')
$hash.TimePeriod = $hash.Window.FindName('TimePeriod')
$hash.ErrorsOnly = $hash.Window.FindName('ErrorsOnly')
$hash.SuccessCode = $hash.Window.FindName('SuccessCode')
$hash.DisabledSteps = $hash.Window.FindName('DisabledSteps')
$hash.ComputerName = $hash.Window.FindName('ComputerName')
$hash.BuildExt = $hash.Window.FindName('BuildExt')
$hash.ActionName = $hash.Window.FindName('ActionName')
$hash.RefreshPeriod = $hash.Window.FindName('RefreshPeriod')
$hash.RefreshNow = $hash.Window.FindName('RefreshNow')
$hash.DataGrid = $hash.Window.FindName('DataGrid')
$hash.ActionOutput = $hash.Window.FindName('ActionOutput')
$hash.MDTGroupBox = $hash.Window.FindName('MDTGroupBox')
$hash.MDTIntegrated = $hash.Window.FindName('MDTIntegrated')
$hash.DeploymentStatus = $hash.Window.FindName('DeploymentStatus')
$hash.CurrentStep = $hash.Window.FindName('CurrentStep')
$hash.StepName = $hash.Window.FindName('StepName')
$hash.PercentComplete = $hash.Window.FindName('PercentComplete')
$hash.MDTStartTime = $hash.Window.FindName('MDTStartTime')
$hash.MDTEndTime = $hash.Window.FindName('MDTEndTime')
$hash.MDTElapsedTime = $hash.Window.FindName('MDTElapsedTime')
$hash.SettingsButton = $hash.Window.FindName('SettingsButton')
$hash.ReportButton = $hash.Window.FindName('ReportButton')
$hash.ErrorCount = $hash.Window.FindName('ErrorCount')
$hash.DeploymentStatusLabel = $hash.Window.FindName('DeploymentStatusLabel')
$hash.CurrentStepLabel = $hash.Window.FindName('CurrentStepLabel')
$hash.StepNameLabel = $hash.Window.FindName('StepNameLabel')
$hash.PercentCompleteLabel = $hash.Window.FindName('PercentCompleteLabel')
$hash.StartLabel = $hash.Window.FindName('StartLabel')
$hash.EndLabel = $hash.Window.FindName('EndLabel')
$hash.ElapsedLabel = $hash.Window.FindName('ElapsedLabel')
$hash.ProgressLabel = $hash.Window.FindName('ProgressLabel')
$hash.ProgressBar = $hash.Window.FindName('ProgressBar')
if (Test-Path -Path "$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico")
{
$hash.Window.Icon = "$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico"
}
if (Test-Path -Path "${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico")
{
$hash.Window.Icon = "${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico"
}
if (Test-Path -Path "$currentLocation\Grid.ico")
{
$hash.Window.add_Loaded({
$hash.Window.Icon = "$currentLocation\Grid.ico"
})
#$hash.Window.TaskbarItemInfo.Overlay = "$currentLocation\Grid.ico"
}
### Settings Window ###
[xml]$xaml2 = Get-Content ($currentLocation + "\XAML\Config.xaml")
$reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $xaml2)
$hash.Window2 = [Windows.Markup.XamlReader]::Load( $reader )
$hash.SQLServer = $hash.Window2.FindName('SQLServer')
$hash.Database = $hash.Window2.FindName('Database')
$hash.MDT = $hash.Window2.FindName('MDT')
$hash.MDTURL = $hash.Window2.FindName('MDTURL')
$hash.ConnectSQL = $hash.Window2.FindName('ConnectSQL')
$hash.TSList = $hash.Window2.FindName('TSList')
$hash.StartDate = $hash.Window2.FindName('StartDate')
$hash.EndDate = $hash.Window2.FindName('EndDate')
$hash.GenerateReport = $hash.Window2.FindName('GenerateReport')
$hash.SettingsTab = $hash.Window2.FindName('SettingsTab')
$hash.ReportTab = $hash.Window2.FindName('ReportTab')
$hash.Tabs = $hash.Window2.FindName('Tabs')
$hash.Working = $hash.Window2.FindName('Working')
$hash.Runasadmin = $hash.Window2.FindName('Runasadmin')
$hash.ReportProgress = $hash.Window2.FindName('ReportProgress')
$hash.Link1 = $hash.Window2.FindName('Link1')
$hash.DTFormat = $hash.Window2.FindName('DTFormat')
if (Test-Path -Path "$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico")
{
#$hash.Window2.Icon = "$env:ProgramFiles\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico"
$Hash.Window2.ShowInTaskbar = $true
}
if (Test-Path -Path "${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico")
{
#$hash.Window2.Icon = "${env:ProgramFiles(x86)}\SMSAgent\ConfigMgr Task Sequence Monitor\Grid.ico"
$Hash.Window2.ShowInTaskbar = $true
}
if (Test-Path -Path "$currentLocation\Grid.ico")
{
#$hash.Window2.Icon = "$currentLocation\Grid.ico"
$Hash.Window2.ShowInTaskbar = $true
}
$script:SQLServer = $hash.SQLServer.Text
$Script:Database = $hash.Database.Text
#endregion
#region Icons and Runspacepool
# Output SystemIcons to bmps
$icons = @()
$global:greentickiconpath = "$env:temp\GreenTick.bmp"
$icons += $greentickiconpath
$global:redcrossiconpath = "$env:temp\RedCross.bmp"
$icons += $redcrossiconpath
if (!(Test-Path $greentickiconpath))
{
$global:greentickicon = [System.IconExtractor]::Extract('comres.dll',8,$true).ToBitmap()
$greentickicon.save("$greentickiconpath")
}
if (!(Test-Path $redcrossiconpath))
{
$global:redcrossicon = [System.IconExtractor]::Extract('comres.dll',10,$true).ToBitmap()
$redcrossicon.save("$redcrossiconpath")
}
$script:RunspacePool = [runspacefactory]::CreateRunspacePool()
$RunspacePool.ApartmentState = 'STA'
$RunspacePool.ThreadOptions = 'ReUseThread'
$RunspacePool.Open()
#endregion
#region Functions
Function Get-DateTimeFormat
{
if ([System.TimeZone]::CurrentTimeZone.IsDaylightSavingTime($(Get-Date)))
{
$TimeZone = [System.TimeZone]::CurrentTimeZone.DaylightName
}
Else
{
$TimeZone = [System.TimeZone]::CurrentTimeZone.StandardName
}
#$Global:Timezones = @()
$obj = New-Object -TypeName psobject -Property @{
TimeZone = 'UTC'
}
$Global:Timezones = [Array]$Timezones + $obj
$obj = New-Object -TypeName psobject -Property @{
TimeZone = $TimeZone
}
$Global:Timezones = [Array]$Timezones + $obj
}
Function Get-TaskSequenceList
{
# Set variables
$script:SQLServer = $hash.SQLServer.Text
$Script:Database = $hash.Database.Text
# If SQLinstance not populated, ask for connection
if ($SQLServer -eq '<SQLServer\Instance>')
{
$hash.ActionOutput.Text = 'No SQL Server defined. Click Settings, and set the SQL Server, database and MDT URL if applicable.'
return
}
# Connect to SQL server
try
{
$connectionString = "Server=$SQLServer;Database=$Database;Integrated Security=SSPI;"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$hash.ActionOutput.Text = 'Connected to SQL Server database. Select a Task Sequence.'
}
catch
{
$hash.ActionOutput.Text = '[ERROR} Could not connect to SQL Server database!'
return
}
# Run SQL query
$Query = "
SELECT DISTINCT summ.SoftwareName AS 'Task Sequence'
FROM vDeploymentSummary summ
WHERE (summ.FeatureType=7)
ORDER BY summ.SoftwareName
"
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$table = New-Object -TypeName 'System.Data.DataTable'
$table.Load($result)
$connection.Close()
# Load data into psobject
$global:Views = @()
Foreach ($Row in $table.Rows)
{
$obj = New-Object -TypeName psobject
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'TS' -Value $Row.'Task Sequence'
$global:Views = [Array]$Views + $obj
}
# Output to Task Sequence combobox
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.TaskSequence.ItemsSource = [Array]$Views.TS
})
}
Function Get-TaskSequenceData
{
param ($hash,$RunspacePool)
$code =
{
param($hash,$SQLServer,$Database,$BuildExtVersionSql,$TimePeriod,$SuccessCode,$ErrorsOnly,$DisabledSteps,$ComputerName,$ActionName,$TS,$MDTIntegrated,$URL,$DTFormat)
# Notify of data retrieval
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.ActionOutput.Text = 'Retrieving data...'
$hash.DataGrid.ItemsSource = ''
})
# Set variable values
if ($MyGUID)
{
Remove-Variable -Name MyGuid
}
if ($Unknowns) # put after display ####
{
Remove-Variable -Name Unknowns
}
if ($ErrorsOnly -eq 'True')
{
$ExitCode = $SuccessCode
}
else
{
$ExitCode = 999999999999999999999999
}
if ($DisabledSteps -eq 'True')
{
$DisabledStep = "''"
}
Else
{
$DisabledStep = '11128'
}
if ($ComputerName -eq '-All-' -or $ComputerName -eq '' -or $ComputerName -eq $Null)
{
$SQLComputerName = '%'
}
Else
{
$SQLComputerName = $ComputerName
}
if ($ActionName -eq '-All-' -or $ActionName -eq '' -or $ActionName -eq $Null)
{
$SQLActionName = '%'
}
Else
{
$SQLActionName = $ActionName
}
$greentickiconpath = "$env:temp\GreenTick.bmp"
$redcrossiconpath = "$env:temp\RedCross.bmp"
# Connect to SQL server
try
{
$connectionString = "Server=$SQLServer;Database=$Database;Integrated Security=SSPI;"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
}
catch
{
$MyError = $_.Exception.Message
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.ActionOutput.Text = "[ERROR} Could not connect to SQL Server database! $MyError"
})
return
}
if ($MDTIntegrated -eq 'True')
{
# Get Unknown Computers from ConfigMgr database if there are any
$Query = "
Select Distinct Name0,
SMBIOS_GUID0 as 'GUID'
from vSMS_TaskSequenceExecutionStatus tes
inner join v_R_System sys on tes.ResourceID = sys.ResourceID
inner join v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) < $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
--and Name0 like '$SQLComputerName'
--and ActionName like '$SQLActionName'
and ExitCode not in ($ExitCode)
and tes.LastStatusMsgID not in ($DisabledStep)
ORDER BY Name0 Desc
"
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$table = New-Object -TypeName 'System.Data.DataTable'
$table.Load($result)
# Gather unknowns into PS object
$UnknownComputers = @()
Foreach ($Row in $table.Rows | Where-Object -FilterScript {
$_.Name0 -eq 'Unknown'
})
{
$obj = New-Object -TypeName psobject
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ComputerName' -Value $Row.Name0
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GUID' -Value $Row.GUID
$UnknownComputers += $obj
}
# If there are unknowns, get computername from MDT
if ($UnknownComputers.Count -ge 1)
{
$URL1 = $URL.Replace('Computers','ComputerIdentities')
# Get ID numbers and Identifiers (GUIDs)
function GetMDTIDs
{
param ($URL)
$Data = Invoke-RestMethod -Uri $URL
foreach($property in ($Data.content.properties) )
{
New-Object -TypeName PSObject -Property @{
ID = $($property.ID.'#text')
Identifier = $($property.Identifier)
}
}
}
# Filter out only the GUIDs
$MDTIDs = GetMDTIDs -URL $URL1 |
Select-Object -Property * |
Where-Object -FilterScript {
$_.Identifier -like '*-*'
} |
Sort-Object -Property ID
$MDTComputerIDs = @()
Foreach ($Computer in $UnknownComputers)
{
$MDTComputerID = $MDTIDs |
Where-Object -FilterScript {
$_.Identifier -eq $Computer.GUID
} |
Select-Object -Property ID, Identifier
$MDTComputerIDs += $MDTComputerID
}
# Get ComputerNames from MDT
function GetMDTComputerNames
{
param ($URL)
$Data = Invoke-RestMethod -Uri $URL
foreach($property in ($Data.content.properties) )
{
New-Object -TypeName PSObject -Property @{
Name = $($property.Name)
ID = $($property.ID.'#text')
}
}
}
# Filter out the computer names from the IDs
$MDTComputers = GetMDTComputerNames -URL $URL |
Select-Object -Property * |
Sort-Object -Property ID
$ResolvedComputerNames = @()
Foreach ($MDTComputerID in $MDTComputerIDs)
{
$MDTComputerName = $MDTComputers |
Where-Object -FilterScript {
$_.ID -eq $MDTComputerID.ID
} |
Select-Object -ExpandProperty Name
$GUID = $MDTIDs |
Where-Object -FilterScript {
$_.ID -eq $MDTComputerID.ID
} |
Select-Object -ExpandProperty Identifier
$obj = New-Object -TypeName PSObject
Add-Member -InputObject $obj -MemberType NoteProperty -Name ComputerName -Value $MDTComputerName
Add-Member -InputObject $obj -MemberType NoteProperty -Name GUID -Value $GUID
$ResolvedComputerNames += $obj
}
}
foreach ($Computer in $ResolvedComputerNames)
{
if ($ComputerName -eq $Computer.ComputerName)
{
$MyGUID = $Computer.GUID
}
}
}
# Get TS execution data from ConfigMgr
if ($MyGUID)
{
$Query = "
Select Distinct sys.Name0 as 'Computer Name',
sys.SMBIOS_GUID0 as 'GUID',
tsp.Name as 'Task Sequence',
comp.UserName0,
CASE
WHEN cmcbs.CNIsOnInternet = 0 THEN 'Intranet'
WHEN cmcbs.CNIsOnInternet = 1 THEN 'Internet'
ELSE CAST(cmcbs.CNIsOnInternet AS varchar)
END as [Connection Type],
CAST(
CASE
$($BuildExtVersionSql -join "`n")
ELSE sys.BuildExt
END AS char) as BuildExt,
comp.Model0,
BIOS.SMBIOSBIOSVersion0 as BIOSVersion,
ExecutionTime,
Step,
tes.ActionName,
GroupName,
tes.LastStatusMsgName,
ExitCode,
ActionOutput
from vSMS_TaskSequenceExecutionStatus tes
INNER JOIN v_R_System sys on tes.ResourceID = sys.ResourceID
INNER JOIN (select MachineID, Name, CNIsOnInternet, LastPolicyRequest, LastDDR as [Last Heartbeat],
LastHardwareScan, max(CNLastOnlinetime) as [Last Online Time]
FROM v_CollectionMemberClientBaselineStatus
GROUP BY Name, MachineID, CNIsOnInternet, ClientVersion, LastPolicyRequest, LastDDR,
LastHardwareScan, CNLastOnlinetime) cmcbs ON cmcbs.MachineID = sys.ResourceID
--INNER JOIN v_CollectionMemberClientBaselineStatus cmcbs ON cmcbs.MachineID = sys.ResourceID
LEFT JOIN v_GS_COMPUTER_SYSTEM comp ON comp.ResourceID = sys.ResourceID
LEFT JOIN v_GS_PC_BIOS BIOS ON BIOS.ResourceID = sys.ResourceID
INNER JOIN v_RA_System_MACAddresses mac on tes.ResourceID = mac.ResourceID
INNER JOIN v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) <= $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
--and sys.Name0 like '$SQLComputerName'
--and ActionName like '$SQLActionName'
and sys.SMBIOS_GUID0 = '$MyGUID'
and ExitCode not in ($ExitCode)
and tes.LastStatusMsgID not in ($DisabledStep)
ORDER BY ExecutionTime Desc
"
$ErrQuery = "
Select Count(Name0) as 'Count' from (Select DISTINCT (Name0), ActionName, ExecutionTime
from vSMS_TaskSequenceExecutionStatus tes
inner join v_R_System sys on tes.ResourceID = sys.ResourceID
inner join v_RA_System_MACAddresses mac on tes.ResourceID = mac.ResourceID
inner join v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) <= $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
--and Name0 like '$SQLComputerName'
--and ActionName like '$SQLActionName'
and sys.SMBIOS_GUID0 = '$MyGUID'
and ExitCode not in ($SuccessCode)) as t
"
}
if (!$MyGUID)
{
$Query = "
Select Distinct sys.Name0 as 'Computer Name',
sys.SMBIOS_GUID0 as 'GUID',
tsp.Name as 'Task Sequence',
comp.UserName0,
CASE
WHEN cmcbs.CNIsOnInternet = 0 THEN 'Intranet'
WHEN cmcbs.CNIsOnInternet = 1 THEN 'Internet'
ELSE CAST(cmcbs.CNIsOnInternet AS varchar)
END as [Connection Type],
CAST(
CASE
$($BuildExtVersionSql -join "`n")
ELSE sys.BuildExt
END AS char) as BuildExt,
comp.Model0,
BIOS.SMBIOSBIOSVersion0 as BIOSVersion,
ExecutionTime,
Step,
tes.ActionName,
GroupName,
tes.LastStatusMsgName,
ExitCode,
ActionOutput
from vSMS_TaskSequenceExecutionStatus tes
INNER JOIN v_R_System sys on tes.ResourceID = sys.ResourceID
INNER JOIN (select MachineID, Name, CNIsOnInternet, LastPolicyRequest, LastDDR as [Last Heartbeat],
LastHardwareScan, max(CNLastOnlinetime) as [Last Online Time]
FROM v_CollectionMemberClientBaselineStatus
GROUP BY Name, MachineID, CNIsOnInternet, ClientVersion, LastPolicyRequest, LastDDR,
LastHardwareScan, CNLastOnlinetime) cmcbs ON cmcbs.MachineID = sys.ResourceID
--INNER JOIN v_CollectionMemberClientBaselineStatus cmcbs ON cmcbs.MachineID = sys.ResourceID
LEFT JOIN v_GS_COMPUTER_SYSTEM comp ON comp.ResourceID = sys.ResourceID
LEFT JOIN v_GS_PC_BIOS BIOS ON BIOS.ResourceID = sys.ResourceID
INNER JOIN v_RA_System_MACAddresses mac on tes.ResourceID = mac.ResourceID
INNER JOIN v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) <= $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
and sys.Name0 like '$SQLComputerName'
and ActionName like '$SQLActionName'
and ExitCode not in ($ExitCode)
and tes.LastStatusMsgID not in ($DisabledStep)
ORDER BY ExecutionTime Desc
"
$ErrQuery = "
Select Count(Name0) as 'Count' from (Select DISTINCT (Name0), ActionName, ExecutionTime
from vSMS_TaskSequenceExecutionStatus tes
inner join v_R_System sys on tes.ResourceID = sys.ResourceID
inner join v_RA_System_MACAddresses mac on tes.ResourceID = mac.ResourceID
inner join v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) <= $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
and Name0 like '$SQLComputerName'
and ActionName like '$SQLActionName'
and ExitCode not in ($SuccessCode)) as t
"
}
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$table = New-Object -TypeName 'System.Data.DataTable'
$table.Load($result)
$command = $connection.CreateCommand()
$command.CommandText = $ErrQuery
$erresult = $command.ExecuteReader()
$errtable = New-Object -TypeName 'System.Data.DataTable'
$errtable.Load($erresult)
$connection.Close()
if ($table.rows.Count -lt 1)
{
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.ActionOutput.Text = 'No results.'
#$hash.ActionOutput.Text = $query
})
return
}
# Gather results into psobject
$global:Results = @()
$i = 0
Foreach ($Row in $table.Rows)
{
$obj = New-Object -TypeName psobject
$i ++
if ($Row.ExitCode -in $SuccessCode.Replace(" ", "").Split(","))
{
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Icon' -Value $greentickiconpath
}
if ($Row.ExitCode -notin $SuccessCode.Replace(" ", "").Split(","))
{
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Icon' -Value $redcrossiconpath
}
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ComputerName' -Value $Row.'Computer Name'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GUID' -Value $Row.'GUID'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Connection Type' -Value $Row.'Connection Type'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'BuildExt' -Value $Row.'BuildExt'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Model0' -Value $Row.'Model0'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'BIOSVersion' -Value $Row.'BIOSVersion'
if ($DTFormat -eq 'UTC')
{
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ExecutionTime' -Value $Row.'ExecutionTime'
}
Else
{
$extime = [System.TimeZone]::CurrentTimeZone.ToLocalTime($($Row.'ExecutionTime' | Get-Date))
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ExecutionTime' -Value $extime
}
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Step' -Value $Row.'Step'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ActionName' -Value $Row.'ActionName'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GroupName' -Value $Row.'GroupName'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'LastStatusMsgName' -Value $Row.'LastStatusMsgName'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ExitCode' -Value $Row.'ExitCode'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ActionOutput' -Value $Row.'ActionOutput'
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Record' -Value $i
$Results += $obj
}
if ($Results.Count -eq 1)
{
$obj = New-Object -TypeName psobject
$i ++
if ($Row.ExitCode -in $SuccessCode.Replace(" ", "").Split(","))
{
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Icon' -Value $greentickiconpath
}
if ($Row.ExitCode -notin $SuccessCode.Replace(" ", "").Split(","))
{
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Icon' -Value $redcrossiconpath
}
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ComputerName' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GUID' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Connection Type' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'BuildExt' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Model0' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'BIOSVersion' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ExecutionTime' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Step' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ActionName' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GroupName' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'LastStatusMsgName' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ExitCode' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ActionOutput' -Value ' '
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'Record' -Value ' '
$Results += $obj
}
$FilteredResults = $Results | Select-Object -Property Icon, ComputerName, GUID, 'Connection Type', BuildExt, Model0, BIOSVersion, ExecutionTime, Step, ActionName, GroupName, LastStatusMsgName, ExitCode, Record
if (!$MyGUID -and $ComputerName -in ('-ALL-', '', $Null))
{
if ($FilteredResults.ComputerName -match 'unknown')
{
foreach ($Computer in $ResolvedComputerNames)
{
$Unknowns = $FilteredResults | Where-Object -FilterScript {
$_.ComputerName -eq 'Unknown' -and $_.GUID -eq $Computer.GUID
}
$i = -1
do
{
$i ++
$Unknowns[$i].ComputerName = $Computer.ComputerName
}
until ($i -eq ($Unknowns.Count -1))
}
}
}
if ($MyGUID)
{
$Unknowns = $FilteredResults | Where-Object -FilterScript {
$_.ComputerName -eq 'Unknown' -and $_.GUID -eq $MyGUID
}
if ($Unknowns)
{
$i = -1
do
{
$i ++
$Unknowns[$i].ComputerName = $ComputerName
}
until ($i -eq ($Unknowns.Count -1))
}
}
# Display results in datagrid
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.DataGrid.ItemsSource = $FilteredResults
$hash.ErrorCount.Text = $errtable.Count
$hash.ActionOutput.Text = 'Click any step to see the action output.'
})
}
# Set variables from Hash table
$SQLServer = $hash.SQLServer.Text
$Database = $hash.Database.Text
$TimePeriod = $hash.TimePeriod.Text
$SuccessCode = $hash.SuccessCode.Text
$ErrorsOnly = $hash.ErrorsOnly.IsChecked
$DisabledSteps = $hash.DisabledSteps.IsChecked
$ComputerName = $hash.ComputerName.SelectedItem
$ActionName = $hash.ActionName.SelectedItem
$TS = $hash.TaskSequence.SelectedItem
$MDTIntegrated = $hash.MDTIntegrated.IsChecked
$URL = $hash.MDTURL.Text
$DTFormat = $hash.DTFormat.SelectedItem
# Create PS instance in runspace pool and execute
$PSinstance = [powershell]::Create().AddScript($code).AddArgument($hash).AddArgument($SQLServer).AddArgument($Database).AddArgument($BuildExtVersionSql).AddArgument($TimePeriod).AddArgument($SuccessCode).AddArgument($ErrorsOnly).AddArgument($DisabledSteps).AddArgument($ComputerName).AddArgument($ActionName).AddArgument($TS).AddArgument($MDTIntegrated).AddArgument($URL).AddArgument($DTFormat)
$PSInstances += $PSinstance
$PSinstance.RunspacePool = $RunspacePool
$PSinstance.BeginInvoke()
}
Function Populate-ActionOutput
{
param ($hash,$RunspacePool)
$code =
{
param($hash,$Record)
$msg = $Results |
Select-Object -Property * |
Where-Object -FilterScript {
$_.Record -eq $Record
}
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.ActionOutput.Text = $msg.ActionOutput
})
}
# Set variables from Hash table
$Record = $hash.DataGrid.SelectedItem.Record
# Create PS instance in runspace pool and execute
$PSinstance = [powershell]::Create().AddScript($code).AddArgument($hash).AddArgument($Record)
$PSInstances += $PSinstance
$PSinstance.RunspacePool = $RunspacePool
$PSinstance.BeginInvoke()
}
Function Populate-ComputerNames
{
param ($hash,$RunspacePool)
$code =
{
param($hash,$SQLServer,$Database,$BuildExtVersionSql,$TimePeriod,$SuccessCode,$ErrorsOnly,$DisabledSteps,$TS,$MDTIntegrated,$URL)
# Set variable values
if ($ErrorsOnly -eq 'True')
{
$ExitCode = $SuccessCode
}
else
{
$ExitCode = 999999999999999999999999
}
if ($DisabledSteps -eq 'True')
{
$DisabledStep = "''"
}
Else
{
$DisabledStep = '11128'
}
# Connect to SQL Server
$connectionString = "Server=$SQLServer;Database=$Database;Integrated Security=SSPI;"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
# Run SQL query
$Query = "
Select Distinct Name0,
SMBIOS_GUID0 as 'GUID',
CAST(
CASE
$($BuildExtVersionSql -join "`n")
ELSE sys.BuildExt
END AS char) as BuildExt
from vSMS_TaskSequenceExecutionStatus tes
inner join v_R_System sys on tes.ResourceID = sys.ResourceID
inner join v_TaskSequencePackage tsp on tes.PackageID = tsp.PackageID
where tsp.Name = '$TS'
--and DATEDIFF(hour,ExecutionTime,GETDATE()) <= $TimePeriod
and DATEDIFF(hour,(CONVERT(datetime, SWITCHOFFSET(CONVERT(datetimeoffset, ExecutionTime), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) ),GETDATE()) <= $TimePeriod
--and Name0 like '$SQLComputerName'
and ExitCode not in ($ExitCode)
and tes.LastStatusMsgID not in ($DisabledStep)
ORDER BY Name0 Desc
"
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$table = New-Object -TypeName 'System.Data.DataTable'
$table.Load($result)
$connection.Close()
# Gather results into PS object
$PCResults = @()
Foreach ($Row in $table.Rows)
{
$obj = New-Object -TypeName psobject
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'ComputerName' -Value $Row.Name0
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'GUID' -Value $Row.GUID
Add-Member -InputObject $obj -MemberType NoteProperty -Name 'BuildExt' -Value $Row.BuildExt
$PCResults += $obj
}
# For each 'Unknown' computer in the list, get the PC name from MDT
if ($MDTIntegrated -eq 'true')
{
$URL1 = $URL.Replace('Computers','ComputerIdentities')
# Get ID numbers and Identifiers (GUIDs)
function GetMDTIDs
{
param ($URL)
$Data = Invoke-RestMethod -Uri $URL
foreach($property in ($Data.content.properties) )
{
New-Object -TypeName PSObject -Property @{
ID = $($property.ID.'#text')
Identifier = $($property.Identifier)
}
}
}
# Filter out only the GUIDs
$MDTIDs = GetMDTIDs -URL $URL1 |
Select-Object -Property * |
Where-Object -FilterScript {
$_.Identifier -like '*-*'
} |
Sort-Object -Property ID
$UnknownComputers = $PCResults | Where-Object -FilterScript {
$_.ComputerName -eq 'Unknown'
}
$MDTComputerIDs = @()
Foreach ($Computer in $UnknownComputers)
{
$MDTComputerID = $MDTIDs |
Where-Object -FilterScript {
$_.Identifier -eq $Computer.GUID
} |
Select-Object -Property ID
$MDTComputerIDs += $MDTComputerID
}
# Get ComputerNames from MDT
function GetMDTComputerNames
{
param ($URL)
$Data = Invoke-RestMethod -Uri $URL
foreach($property in ($Data.content.properties) )
{
New-Object -TypeName PSObject -Property @{
Name = $($property.Name)
ID = $($property.ID.'#text')
}
}
}
# Filter out the computer names from the IDs
$MDTComputers = GetMDTComputerNames -URL $URL |
Select-Object -Property * |
Sort-Object -Property ID
$AdditionalComputerNames = @()
Foreach ($MDTComputerID in $MDTComputerIDs)
{
$MDTComputerName = $MDTComputers |
Where-Object -FilterScript {
$_.ID -eq $MDTComputerID.ID
} |
Select-Object -ExpandProperty Name
$AdditionalComputerNames += $MDTComputerName.ToUpper()
}
$ConfigMgrList = $PCResults |
Select-Object -Property ComputerName |
Where-Object -FilterScript {
$_.ComputerName -ne 'Unknown'
}
$FinalComputerNameList = @()
$FinalComputerNameList += $ConfigMgrList.ComputerName
$FinalComputerNameList += $AdditionalComputerNames
$BuildVersions = [String]::Join('; ', (($PCResults | Select-Object -Property BuildExt).BuildExt | Group-Object | Sort-Object Count -Descending | ForEach-Object {$_ | select * } ))
}
# Add a wildcard option and add only ConfigMgr results if MDT not enabled
if ($MDTIntegrated -eq $false)
{
$FinalComputerNameList = @()
#$PCResults = $PCResults | Select-Object -ExpandProperty ComputerName
$FinalComputerNameList += $PCResults | Select-Object -ExpandProperty ComputerName
$BuildVersions = [String]::Join('; ', @($PCResults | Select-Object -Property BuildExt | Group-Object BuildExt | Sort-Object Count -Descending | ForEach-Object { "$($_.Name.Trim()) = $($_.Count)" }) )
}
$FinalComputerNameList += '-All-'
# Display results in ComputerName comboxbox
$hash.Window.Dispatcher.Invoke(
[action]{
$hash.ComputerName.ItemsSource = [Array]$FinalComputerNameList
$hash.BuildExt.Text = $BuildVersions
})
}
# Set variables from Hash table
$SQLServer = $hash.SQLServer.Text
$Database = $hash.Database.Text
$TimePeriod = $hash.TimePeriod.Text
$SuccessCode = $hash.SuccessCode.Text
$ErrorsOnly = $hash.ErrorsOnly.IsChecked
$DisabledSteps = $hash.DisabledSteps.IsChecked
$TS = $hash.TaskSequence.SelectedItem
$MDTIntegrated = $hash.MDTIntegrated.IsChecked
$URL = $hash.MDTURL.Text
# Create PS instance in runspace pool and execute
$PSinstance = [powershell]::Create().AddScript($code).AddArgument($hash).AddArgument($SQLServer).AddArgument($Database).AddArgument($BuildExtVersionSql).AddArgument($TimePeriod).AddArgument($SuccessCode).AddArgument($ErrorsOnly).AddArgument($DisabledSteps).AddArgument($TS).AddArgument($MDTIntegrated).AddArgument($URL)
$PSInstances += $PSinstance
$PSinstance.RunspacePool = $RunspacePool
$PSinstance.BeginInvoke()
}
Function Populate-ActionNames
{
param ($hash,$RunspacePool)
$code =
{
param($hash,$SQLServer,$Database,$TimePeriod,$SuccessCode,$ErrorsOnly,$DisabledSteps,$TS)
# Set variable values