forked from DexterPOSH/PS_ConfigMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
POSH-Deploy_WMI.ps1
1719 lines (1464 loc) · 80 KB
/
POSH-Deploy_WMI.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.0
Set-StrictMode -Version latest
$VerbosePreference = 'continue' #setting this as all the verbose messages are displayed on the background console window (hidden by default)
<#
Credits - Below links have been very helpful
http://stackoverflow.com/questions/21935398/powershell-observablecollection-predicate-filter
PowerShell MVP- Boe Prox's post on WPF
http://learn-powershell.net/tag/wpf/
#>
#region XAML definition
[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="POSH-Deploy v1 - by DexterPOSH" Height="748" Width="1272" ResizeMode="NoResize" Background="#FF5397B4">
<Grid Height="713" Width="1253" Background="#FF5397B4">
<Label Content="Choose action[ Add/ Remove machines to collection]" Height="28" HorizontalAlignment="Left" Margin="10,10,0,0" Name="labelAction" VerticalAlignment="Top" Width="320" />
<Label Content="Enter Machine Names (one per line)" Height="28" HorizontalAlignment="Left" Margin="421,10,0,0" Name="labelMachine" VerticalAlignment="Top" Width="222" />
<Button Content="Action" Height="67" HorizontalAlignment="Left" Margin="699,31,0,0" Name="buttonaction" VerticalAlignment="Top" Width="75" ToolTip="Add/ Remove Machine name from the Query Rules" />
<TextBox Height="113" HorizontalAlignment="Left" Margin="421,31,0,0" Name="textBoxComputer" VerticalAlignment="Top" Width="203" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" ToolTip="Add Machine Name (one per line)" />
<CheckBox Content="Add Name to Query" Height="30" HorizontalAlignment="Left" Margin="34,42,0,0" Name="checkBoxAdd" VerticalAlignment="Top" Width="144" ToolTip="Check this if want to add machine names to the Collection" />
<CheckBox Content="Remove Name from Query" Height="30" HorizontalAlignment="Left" Margin="228,42,0,0" Name="checkBoxRemove" VerticalAlignment="Top" Width="162" />
<StackPanel Height="515" HorizontalAlignment="Left" Margin="12,152,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="762">
<TabControl Height="514" Name="tabControl1" Width="765">
<TabItem Header="Device Collections" Name="tabDeviceCollections">
<Grid>
<DataGrid Name="dataGridApps" RowHeight="30" ColumnWidth="100" GridLinesVisibility="Horizontal" HeadersVisibility="All" AutoGenerateColumns="True" ClipToBounds="True" HorizontalContentAlignment="Center" FontSize="13" ToolTip="Double Click on a Row to select" IsReadOnly="True" Margin="-2,0,-4,4" />
</Grid>
</TabItem>
<TabItem Header="User Collections" Name="tabUserCollections">
<DataGrid Name="dataGridUsers" RowHeight="30" ColumnWidth="100" GridLinesVisibility="Horizontal" HeadersVisibility="All" AutoGenerateColumns="True" ClipToBounds="True" HorizontalContentAlignment="Center" FontSize="13" ToolTip="Double Click on a Row to select" IsReadOnly="True" Margin="-2,0,-4,4" />
</TabItem>
</TabControl>
</StackPanel>
<DataGrid AutoGenerateColumns="True" Height="305" HorizontalAlignment="Left" Margin="812,362,0,0" Name="dataGridSelectedApps" VerticalAlignment="Top" Width="415" SelectionUnit="CellOrRowHeader" ToolTip="double click on a row to un-select it" IsReadOnly="True" />
<Label Content="default -current user" Height="38" HorizontalAlignment="Left" Margin="1007,0,0,0" Name="labelCreds" VerticalAlignment="Top" Width="134" />
<TextBox Height="30" HorizontalAlignment="Left" Margin="807,31,0,0" Name="textBoxServer" VerticalAlignment="Top" Width="182" ToolTip="Input the SCCM server having SMS namespace provider installed" />
<Label Content="SCCM Server (SMS Namespace)" Height="25" HorizontalAlignment="Left" Margin="810,0,0,0" Name="labelServer" VerticalAlignment="Top" Width="179" />
<Label Content="Select Collections" Height="30" HorizontalAlignment="Left" Margin="16,116,0,0" Name="labelSelectApps" VerticalAlignment="Top" Width="119" />
<Label Content="Log Information" Height="32" HorizontalAlignment="Left" Margin="809,79,0,0" Name="labelLog" VerticalAlignment="Top" Width="230" />
<Label Content="Selected Collections" Height="37" HorizontalAlignment="Left" Margin="807,319,0,0" Name="labelSelectedApps" VerticalAlignment="Top" Width="205" />
<CheckBox Content="Show PS Window" Height="26" HorizontalAlignment="Left" Margin="810,673,0,0" Name="checkBoxPSWindow" VerticalAlignment="Top" Width="136" ToolTip="Shows the PS Console running in background" />
<Button Content="Test SMS Connection" Height="30" HorizontalAlignment="Left" Margin="1113,31,0,0" Name="buttonTestSMSConnection" VerticalAlignment="Top" Width="127" ToolTip="Tests the connectivity to the SMS Namespace (using the creds specified)" />
<TextBox Height="28" HorizontalAlignment="Left" Margin="253,116,0,0" Name="textBoxSearch" VerticalAlignment="Top" Width="150" />
<Label Content="Search Collections" Height="38" HorizontalAlignment="Left" Margin="136,116,0,0" Name="labelSearch" VerticalAlignment="Top" Width="111" />
<Button Content="Copy" Height="30" HorizontalAlignment="Left" Margin="941,319,0,0" Name="buttonCopy" VerticalAlignment="Top" Width="71" ToolTip="Copies the App names in the clipboard" />
<Button Content="Sync Collections List" Height="25" HorizontalAlignment="Left" Margin="34,676,0,0" Name="buttonSyncApps" VerticalAlignment="Top" Width="118" ToolTip="Will fetch all the collections on the SMS Server " IsEnabled="False" />
<Button Content="Clear" Height="30" HorizontalAlignment="Left" Margin="1029,319,0,0" Name="buttonClear" VerticalAlignment="Top" Width="75" ToolTip="Clears the selected app list" />
<CheckBox Content=" Alternate Creds" Height="27" HorizontalAlignment="Left" Margin="1003,34,0,0" Name="checkBoxCred" VerticalAlignment="Top" Width="101" />
<Button Content="Browse" Height="23" HorizontalAlignment="Left" Margin="630,124,0,0" Name="buttonBrowse" VerticalAlignment="Top" Width="72" ToolTip="Browse for file with Machine Names" />
<Label Content="Created by DexterPOSH" Height="31" HorizontalAlignment="Left" Margin="1089,676,0,0" Name="labelName" VerticalAlignment="Top" Width="164" FontSize="14" Foreground="Red"></Label>
<Image Height="36" HorizontalAlignment="Left" Margin="1044,673,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="37" />
<Button Content="Collection Integrity Check" Height="25" HorizontalAlignment="Left" Margin="186,676,0,0" Name="buttonIntegrity" VerticalAlignment="Top" Width="166" ToolTip="Does a check on the last 3 collections in PS_deploy.csv" IsEnabled="False" />
<ListBox Height="208" HorizontalAlignment="Left" Margin="800,105,0,0" Name="listBoxLog" VerticalAlignment="Top" Width="427" ItemsSource="{Binding}" />
<Button Content="ClearLog" Height="24" HorizontalAlignment="Left" Margin="1139,80,0,0" Name="buttonClearLog" VerticalAlignment="Top" Width="88" />
</Grid>
</Window>
"@
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
$reader = (New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $xaml)
$Window = [Windows.Markup.XamlReader]::Load( $reader )
#endregion XAML definition
#region Setup log for the changes made to the Collections
Write-Host -ForegroundColor Red -Object '########################----POSH Deploy----######################## '
Write-Host -ForegroundColor 'Cyan' -Object 'Welcome to the ConfigMgr (SCCM) deployment tool.!!!'
Write-Host -ForegroundColor 'Cyan' -Object 'Designed and Created by Deepak Singh Dhami (@DexterPOSH)'
$host.UI.RawUI.WindowTitle = 'POSH Deploy by DexterPOSH'
$PSdeployfile = "$([System.Environment]::GetFolderPath('MyDocuments'))\PS_Deploy.csv"
#As part of the recovery plan the Tool will log all the deployments to a file PS_Deploy.csv (in User MyDocuments) until the size of it grows older than 10MB
if (Test-Path -Path $PSdeployfile -Type leaf )
{
if ( $((Get-Item -Path $PSdeployfile).length/1MB) -ge 10MB)
{
Write-Verbose -Message "[POSH Deploy] Size exceeded 10MB on $(Get-Date)..so taking backup"
Rename-Item -Path $PSdeployfile -NewName PS_Deploy_bak.csv -Force
}
else
{
Write-Verbose -Message '[POSH Deploy] Size of PS_Deploy.csv is below 5 MB...continuing'
}
}
else
{
Write-Verbose -Message "[POSH Deploy] PS_Deploy.csv not found....creating one in $([System.Environment]::GetFolderPath('MyDocuments'))"
New-Item -Path $PSdeployfile -ItemType file -Verbose
}
#endregion
#region Connect to Control
$buttonaction = $Window.FindName('buttonaction')
$textBoxComputer = $Window.FindName('textBoxComputer')
$checkBoxAdd = $Window.FindName('checkBoxAdd')
$checkBoxRemove = $Window.FindName('checkBoxRemove')
$buttonBrowse = $Window.FindName('buttonBrowse')
$dataGridApps = $Window.FindName('dataGridApps')
$dataGridUsers = $Window.FindName('dataGridUsers')
$dataGridSelectedApps = $Window.FindName('dataGridSelectedApps')
$textBoxServer = $Window.FindName('textBoxServer')
$checkBoxPSWindow = $Window.FindName('checkBoxPSWindow')
$buttonTestSMSConnection = $Window.FindName('buttonTestSMSConnection')
$textBoxSearch = $Window.FindName('textBoxSearch')
$buttonCopy = $Window.FindName('buttonCopy')
$buttonSyncApps = $Window.FindName('buttonSyncApps')
$buttonclear = $Window.FindName('buttonClear')
$checkBoxCred = $Window.FindName('checkBoxCred')
$DexLabel = $Window.FindName('labelName')
$ListBoxLog = $Window.findName('listBoxLog')
$buttonIntegrity = $Window.FindName('buttonIntegrity')
$tabControl = $Window.FindName('tabControl1')
$tabUserCollections = $Window.FindName('tabUserCollections')
$tabDeviceCollections = $Window.FindName('tabDeviceCollections')
$buttonClearLog = $Window.FindName('buttonClearLog')
#endregion Connect to Control
#region Customize the GUI
$LogCollection = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[String]
$ListBoxLog.ItemsSource = [System.Windows.Data.CollectionViewSource]::GetDefaultView($LogCollection)
$LogCollection.Add('Welcome to POSH-Deploy, Enter your SCCM Server name & Hit Test Connection to begin')
$dataGridApps.background = 'LightGray'
$dataGridApps.RowBackground = 'LightYellow'
$dataGridApps.AlternatingRowBackground = 'LightBlue'
$buttonaction.Background = 'Yellow'
$dataGridUsers.background = 'LightGray'
$dataGridUsers.RowBackground = 'LightYellow'
$dataGridUsers.AlternatingRowBackground = 'LightBlue'
$dataGridSelectedApps.background = 'LightGray'
$dataGridSelectedApps.RowBackground = 'LightGreen'
$dataGridSelectedApps.AlternatingRowBackground = 'LightYellow'
$textBoxServer.text = $env:COMPUTERNAME
$collectionView = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[object]
if (Test-Path -Path "$([System.Environment]::GetFolderPath('MyDocuments'))\Collection.csv" )
{
Import-Csv -Path "$([System.Environment]::GetFolderPath('MyDocuments'))\Collection.csv"| ForEach-Object -Process {
$collectionView.Add($_)
}
}
else
{
$LogCollection.Add('Collection.csv not found. After Test Connection, Select Device Collection Tab & Hit Sync Collection List')
}
$UsercollectionView = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[object]
if (Test-Path -Path "$([System.Environment]::GetFolderPath('MyDocuments'))\UserCollection.csv" )
{
Import-Csv -Path "$([System.Environment]::GetFolderPath('MyDocuments'))\UserCollection.csv"| ForEach-Object -Process {
$UsercollectionView.Add($_)
}
}
else
{
$LogCollection.Add('UserCollection.csv not found. After Test Connection, Select User Collection Tab & Hit Sync Collection List')
}
$DeviceCollectionDataGridview = [System.Windows.Data.CollectionViewSource]::GetDefaultView($collectionView)
$filter = ''
$DeviceCollectionDataGridview.Filter = {
param($item) $item -match $filter
}
$DeviceCollectionDataGridview.Refresh()
$UserCollectionDataGridview = [System.Windows.Data.CollectionViewSource]::GetDefaultView($UsercollectionView)
$filter = ''
$UserCollectionDataGridview.Filter = {
param($item) $item -match $filter
}
$UserCollectionDataGridview.Refresh()
$dataGridApps.ItemsSource = $DeviceCollectionDataGridview
$buttonaction.IsEnabled = $false #This will be disabled at start unless the Test SMS Connection is successful
#endregion customize the GUI
#region Function definitions
#region helper Functions
Function Invoke-SCCMServiceCheck
{
[CmdletBinding()]
#[OutputType([System.Int32])]
param(
[Parameter(Position = 0, Mandatory = $true,
helpmessage = 'Enter the ComputerNames to refresh machine policy on',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[ValidateNotNullOrEmpty()]
[System.String[]]
$ComputerName
)
BEGIN
{
Function Set-RemoteService
{
[CmdletBinding()]
[OutputType([PSObject])]
param(
[Parameter(Position = 0, Mandatory = $false,
helpmessage = 'Enter the ComputerNames to Chec & Fix Services on',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[String[]]$ComputerName = $env:COMPUTERNAME,
[Parameter(Mandatory = $true,
helpmessage = 'Enter the Service Name (Accepts WQL wildacard)')]
[string]$Name,
[Parameter(Mandatory = $true,helpmessage = 'Enter the state of the Service to be set')]
[ValidateSet('Running','Stopped')]
[string]$state,
[Parameter(Mandatory = $true,helpmessage = 'Enter the Startup Type of the Service to be set')]
[ValidateSet('Automatic','Manual','Disabled')]
[string]$startupType
)
BEGIN
{
Write-Verbose -Message '[Invoke-SCCMServiceCheck][Set-RemoteService] - Starting the Function.'
}
PROCESS
{
foreach ($computer in $ComputerName )
{
Write-Verbose -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - Checking if $Computer is online"
if (Test-Connection -ComputerName $computer -Count 2 -Quiet)
{
Write-Verbose -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer is online"
#region try to set the required state and StartupType of the Service
try
{
$service = Get-WmiObject -Class Win32_Service -ComputerName $computer -Filter "Name LIKE '$Name'" -ErrorAction Stop
#Check the State and set it
if ( $service.State -ne "$state")
{
#Set the State of the Remote Service
switch -exact ($state)
{
'Running'
{
$changestateaction = $service.startService()
Start-Sleep -Seconds 2 #it will require some time to process action
if ($changestateaction.ReturnValue -ne 0 )
{
$err = Invoke-Expression -Command "net helpmsg $($changestateaction.ReturnValue)"
Write-Warning -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer couldn't change state to $state `nWMI Call Returned :$err"
}
break
}
'Stopped'
{
$changestateaction = $service.stopService()
Start-Sleep -Seconds 2
if ($changestateaction.ReturnValue -ne 0 )
{
$err = Invoke-Expression -Command "net helpmsg $($changestateaction.ReturnValue)"
Write-Warning -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer couldn't change state to $state `nWMI Call Returned :$err"
}
break
}
} #end switch
} #end if
#Check the StartMode and set it
if ($service.startMode -ne $startupType)
{
#set the Start Mode of the Remote Service
$changemodeaction = $service.ChangeStartMode("$startupType")
Start-Sleep -Seconds 2
if ($changemodeaction.ReturnValue -ne 0 )
{
$err = Invoke-Expression -Command "net helpmsg $($changemodeaction.ReturnValue)"
Write-Warning -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer couldn't change startmode to $startupType `nWMI Call Returned :$err"
}
} #end if
#Write the Object to the Pipeline
Get-WmiObject -Class Win32_Service -ComputerName $computer -Filter "Name LIKE '$Name'" -ErrorAction Stop | Select-Object -Property @{Label = 'ComputerName';Expression = {
"$($_.__SERVER)"
}
}, @{Label = 'ServiceName';Expression = {
$_.Name
}
}, StartMode, State
}#end try
catch
{
Write-Warning -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer :: $_.exception"
} #end catch
#endregion try to set the required state and StartupType of the Service
}
else
{
Write-Verbose -Message "[Invoke-SCCMServiceCheck][Set-RemoteService] - $Computer is Offline"
}
} #end foreach ($computer in $Computername)
}#end PROCESS
END
{
Write-Verbose -Message '[Invoke-SCCMServiceCheck][Set-RemoteService] - Ending the Function'
}
}
}
PROCESS
{
foreach ($computer in $ComputerName )
{
try
{
#Automatic Updates Service set to Running(Auto)
Set-RemoteService -ComputerName $computer -Name Wuauserv -StartupType Automatic -state Running -ErrorAction Stop
Write-Verbose -Message "Invoke-SCCMServiceCheck : $computer --> Automatic Updates Service Checked"
#WMI Service set to Running(Auto)
Set-RemoteService -ComputerName $computer -Name Winmgmt -StartupType Automatic -state Running -ErrorAction Stop
Write-Verbose -Message "Invoke-SCCMServiceCheck : $computer --> Windows Management Service Checked"
#Remote Registry Service set to Running(Auto)
Set-RemoteService -ComputerName $computer -Name RemoteRegistry -StartupType Automatic -state Running -ErrorAction stop
Write-Verbose -Message "Invoke-SCCMServiceCheck : $computer --> Remote Registry Service Checked"
#SMS Agent Host (CcmExec) Service set to Running(Auto)
Set-RemoteService -ComputerName $computer -Name CcmExec -StartupType Automatic -state Running -ErrorAction stop
Write-Verbose -Message "Invoke-SCCMServiceCheck : $computer --> SMS Agent Host Service Checked"
#BITS Service set to Running(Auto)
Set-RemoteService -ComputerName $computer -Name Bits -StartupType Automatic -state Running -ErrorAction Stop
Write-Verbose -Message "Invoke-SCCMServiceCheck : $computer --> BITS service Checked"
}
catch
{
Write-Warning -Message "Invoke-SCCMServiceCheck : $computer --> One of the SMS service is not running & could not be fixed. "
}
} #end Foreach
} #end PROCESS
}
Function Invoke-MachinePolicyRefresh
{
[CmdletBinding()]
#[OutputType([System.Int32])]
param(
[Parameter(Position = 0, Mandatory = $true,
helpmessage = 'Enter the ComputerNames to refresh machine policy on',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[ValidateNotNullOrEmpty()]
[System.String[]]
$ComputerName
)
PROCESS
{
foreach ($computer in $ComputerName )
{
try
{
$SMSCli = Get-WmiObject -Class SMS_Client -Namespace root\ccm -List #used Get-WMIObject as this will be handled with alternate creds
#$SMSCli = [wmiclass]"\\$computer\root\ccm:sms_client"
$null = $SMSCli.TriggerSchedule('{00000000-0000-0000-0000-000000000021}')
Write-Verbose -Message " Invoke-MachinePolicyRefresh: $computer --> Machine Policy refreshed"
}
catch
{
Write-Warning -Message " Invoke-MachinePolicyRefresh: $computer --> Could not Refresh Machine Policy"
}
} #end foreach
}#end PROCESS
}
Function Connect-SCCMServer
{
# Connect to one SCCM server
[CmdletBinding()]
PARAM (
[Parameter(Mandatory = $false,HelpMessage = 'SCCM Server Name or FQDN',ValueFromPipeline = $true)][Alias('ServerName','FQDN')][String] $SCCMServer = (Get-Content -Path env:computername),
[Parameter(Mandatory = $false,HelpMessage = 'Credentials to use' )][System.Management.Automation.PSCredential]$credential = $null
)
PROCESS {
Write-Verbose -Message '[Connect-SCCMServer] Trying to connect to SCCM server WMI'
#region open a CIM session
$Params = @{ComputerName = $SCCMServer;ErrorAction = 'Stop'}
if ($credential)
{
$Params.Add('Credential',$credential)
}
try
{
#region create the Hash to be used later for WMI queries
$sccmProvider = Get-WmiObject -Query 'select * from SMS_ProviderLocation where ProviderForLocalSite = true' -Namespace 'root\sms' @Params
# Split up the namespace path
$Splits = $sccmProvider.NamespacePath -split '\\', 4
Write-Verbose -Message "[Connect-SCCMServer] Provider is located on $($sccmProvider.Machine) in namespace $($splits[3])"
# Create a new hash to be passed on later
$WMIHash = @{'ComputerName' = $SCCMServer;'NameSpace' = $Splits[3];'ErrorAction' = 'Stop'}
if ( $checkBoxCred.IsChecked)
{
Write-Verbose -Message '[POSH Deploy] Setting the PSDefaultParameterValues for Get-WMIObject to use alternate Creds'
$LogCollection.Add('Setting the PSDefaultParameterValues for Get-WMIObject to use alternate Creds')
$Script:PSDefaultParameterValues = @{'Get-WMIObject:Credential' = $Script:Cred} #setting the Credentials for all the WMI Calls as CIM Session can't be used
}
Write-Output -InputObject $WMIHash
#endregion create the Hash to be used later for CIM queries
}
catch
{
# Write-Warning "[Connect-SCCMServer] Something went wrong"
$LogCollection.Add('Something went wrong while connecting to SMS Provider. Try again')
Write-Warning -Message "[Connect-SCCMServer] $_.exception"
}
Write-Verbose -Message '[Connect-SCCMServer] Ending the Function'
}
}
#endregion
#endregion
#region Hide and Show Console definitions
# Credits to - http://powershell.cz/2013/04/04/hide-and-show-console-window-from-gui/
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Show-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
#5 show
[Console.Window]::ShowWindow($consolePtr, 5)
}
function Hide-Console
{
$consolePtr = [Console.Window]::GetConsoleWindow()
#0 hide
[Console.Window]::ShowWindow($consolePtr, 0)
}
#endregion Hide and Show Console definitions
#region Add-MachineNametoSCCMCollection
function Add-ResourceToSCCMCollection
{
[CmdletBinding(DefaultParameterSetName='Device')]
[OutputType([PSObject])]
Param
(
# Enter the Computer Name
[Parameter(Mandatory,
helpmessage = 'Enter the ComputerNames array to remove from the Collection',
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='Device'
)]
[Alias('CN','computer')]
[String[]]
$ComputerName,
[Parameter(Mandatory,
helpmessage = 'Enter the ComputerNames array to remove from the Collection',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
ParameterSetName='User'
)]
[Alias('SamAccountName','LogonName','Identity')]
[String[]]
$UserName,
#Specify the Collection ID
[Parameter(Mandatory,
ValueFromPipelineByPropertyName)]
[validatenotnullorempty()]
#[ValidatePattern('^[A-Za-z]{3}\w{5}$')]
[string]
$CollectionId,
# Specify the CIM Hash generated by Connect-SCCMServer
[Parameter(Mandatory)]
[validatenotnullorempty()]
[hashtable]$WMIHash
)
Begin
{
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Starting the function'
#ScriptBlock to create a new Query Rule
$createNewAutomatedQueryRule = {
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Auotmated_QuerRule not found for this collection..creating one'
$QueryRuleClass = Get-WmiObject -Class SMS_CollectionRuleQuery -List @WMIHash #Returns back the class Object
$TempQueryRule = $QueryRuleClass.createinstance()
switch -exact ($PSCmdlet.ParameterSetName)
{
'User' {$TempQueryRule.QueryExpression ='select SMS_R_USER.ResourceID,SMS_R_USER.ResourceType,SMS_R_USER.Name,SMS_R_USER.UniqueUserName,SMS_R_USER.WindowsNTDomain from SMS_R_User where SMS_R_User.UserName in ("null")'}
'Device' { $TempQueryRule.QueryExpression = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.NetbiosName in ("null")'}
}
$TempQueryRule.RuleName = 'Automated_QueryRule'
$null = $Collection.AddMembershipRule($TempQueryRule)
$Collection.get()
$QueryRules = $Collection.CollectionRules
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Auotmated_QuerRule Created and saved for the Collection'
$Automated_QueryRule = $QueryRules |
Where-Object -FilterScript {
$_.RuleName -eq 'Automated_QueryRule'
} |
Sort-Object -Property {
$_.QueryExpression.Length
} |
Select-Object -First 1
Write-Output -InputObject $Automated_QueryRule
}
}
Process
{
try
{
$Collection = Get-WmiObject -Class SMS_Collection -Filter "CollectionID='$collectionid'" @Script:WMIHash
Write-Verbose -Message "Add-ResourceToSCCMCollection: Queried the Collection $($collection.name) with CollectionId : $collectionid successfully"
$Collection.Get() #Invoke Get Method to get the Lazy Properties back
#get the Collection Rules in an array
$QueryRules = @($Collection.CollectionRules)
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Queried the QueryRules on the Collection successfully'
}
catch
{
Write-Warning -Message 'Add-ResourceToSCCMCollection: Something went wrong while querying the Collection and the Collection Rules on it'
$LogCollection.Add("Add-ResourceToSCCMCollection: $_.exception")
}
#The Script won't make any changes in the existing query but will only look for a QueryRule by name "Automated_QueryRule
If ($QueryRules)
{
# If already Query Rules exist..then look among them for "automated_queryrule"
If (!($Automated_QueryRule = $QueryRules |
Where-Object -FilterScript {
($_.__Class -eq 'SMS_CollectionRuleQuery')-and ($_.RuleName -eq 'Automated_QueryRule')
} |
Sort-Object -Property {
$_.QueryExpression.Length
} |
Select-Object -First 1))
{
$Automated_QueryRule = & $createNewAutomatedQueryRule
}
}
else
{
#If there are no Query Rules for the Collection go ahead and create one
$Automated_QueryRule = & $createNewAutomatedQueryRule
}
#make the QueryExpression ready for adding machinenames to it
$tempQueryExpression = $Automated_QueryRule.QueryExpression
#remove the last ')' in the QueryRule
$tempQueryExpression = $tempQueryExpression.remove(($tempQueryExpression.length -1 ))
switch -exact ($PSCmdlet.ParameterSetName)
{
'User'
{
Foreach ($user in $UserName)
{
if ($tempQueryExpression -match $user)
{
#this does a basic check to see if the machine name is already addded in the Automated_QueryRule
#Won't check the other QueryRules as ...one can always run the Remove-MachineFromCollection to remove the machine name from all QUeryRules and then add
Write-Verbose -Message "Add-ResourceToSCCMCollection: The machine name $user is already there in the Automated_QueryRule"
}
else
{
Write-Verbose -Message "Add-ResourceToSCCMCollection: Adding machine name $user to the Automated_QueryRule."
#Adds machine name in the body at the end of the query
$tempQueryExpression = $tempQueryExpression + ",`"$user`""
}
} #end Foreach ($computer in $computername)
}
'Device'
{
Foreach ($computer in $ComputerName)
{
if ($tempQueryExpression -match $computer)
{
#this does a basic check to see if the machine name is already addded in the Automated_QueryRule
#Won't check the other QueryRules as ...one can always run the Remove-MachineFromCollection to remove the machine name from all QUeryRules and then add
Write-Verbose -Message "Add-ResourceToSCCMCollection: The machine name $computer is already there in the Automated_QueryRule"
}
else
{
Write-Verbose -Message "Add-ResourceToSCCMCollection: Adding machine name $computer to the Automated_QueryRule."
#Adds machine name in the body at the end of the query
$tempQueryExpression = $tempQueryExpression + ",`"$computer`""
}
} #end Foreach ($computer in $computername)
}
}
#add the last ')' in the QueryRule
$tempQueryExpression = $tempQueryExpression + ')'
#One more check done here to validate the QueryExpression
if ( (Invoke-WmiMethod -Class SMS_CollectionRuleQuery -Name ValidateQuery -ArgumentList $tempQueryExpression @WMIHash).returnvalue )
{
Write-Verbose -Message 'Add-ResourceToSCCMCollection: The QueryExpression is Validated'
}
else
{
$LogCollection.add('Add-ResourceToSCCMCollection: The QueryExpression created is not valid' )
}
if ($($Automated_QueryRule.queryExpression).length -lt $tempQueryExpression.length)
{
#after the text manipulation, save the new query...only if the QueryExpression has been modified
$Automated_QueryRule.queryexpression = $tempQueryExpression
#region log the changes
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Taking the backup in POSH_Deploy.csv'
#Now the QueryExpression has been modified...So before proceeeding take a backup
try
{
[pscustomobject]@{'Collection' = $Collection.Name ;
'CollectionType'= $PSCmdlet.ParameterSetName;
'CollectionId' = $CollectionId;
'Action' = 'Add';
'MachineNames' = [string]$ComputerName;
'QueryName' = 'Automated_QueryRule'; #Adding machine names always done to this QueryRule
'QueryId' = $Automated_QueryRule.QueryId;
'QueryExpression' = $Automated_QueryRule.QueryExpression
}| Export-Csv -NoTypeInformation -Path $PSdeployfile -Append
#Put the QueryRule in PS_Audit.csv
Add-Content -Value "$($Collection.Name); $($Automated_QueryRule.queryexpression)" -Path C:\Temp\PS_Audit.csv
}
catch
{
#If the file is POSH_Deploy.csv is already opened then don't proceed
$LogCollection.Add("Add-ResourceToSCCMCollection: $_.Exception")
}
#endregion log the changes
#region delete the previous Query Rule
#before deleting need to make sure the collection is ready ....Precaution
while ((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -ne 1 )
{
Start-Sleep -Seconds 1
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Collection is not in the ready state, So sleeping for 1 second'
}
#do a check before modifying the collection ---Is the Collection ready ? Someone could be editing the Collection Rules
if(( Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1 )
{
#means the collection is ready for the update
Write-Verbose -Message "Add-ResourceToSCCMCollection: The Automated_QueryRule's QueryExpression is validated....Saving it now"
try
{
# deleting the QueryRule.
$null = $Collection.DeleteMembershipRule($Automated_QueryRule)
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Invoked Method DeleteMembershipRule on the Collection'
$null = $Collection.RequestRefresh()
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Invoked Method RequestRefresh on the Collection'
}
catch
{
Write-Error -Message "Couldn't invoke method DeleteMembershipRule on the Collection with ID $collectionid"
$LogCollection.Add("Add-ResourceToSCCMCollection: $_.exception")
}
}
#endregion
#region Add a new Query Rule
#before deleting need to make sure the collection is ready
do
{
Start-Sleep -Seconds 1
}
until ((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1 )
#do a check before modifying the collection ---Is the Collection ready ?
if((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1)
{
#means the collection is ready for the update
try
{
$null = $Collection.AddmembershipRule($Automated_QueryRule)
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Invoked Method AddMembershipRule on the Collection'
$null = $Collection.RequestRefresh()
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Invoked Method RequestRefresh on the Collection'
}
catch
{
Write-Warning -Message "Add-ResourceToSCCMCollection: Couldn't invoke method AddMembershipRule on the Collection with ID $collectionid"
$LogCollection.Add("Add-ResourceToSCCMCollection: $_.exception ")
}
}
#endregion Add a new Query Rule
} #End if ($($Automated_QueryRule.queryExpression).length -lt $tempQueryExpression.length)
else
{
Write-Verbose -Message 'Add-ResourceToSCCMCollection: The QueryExpression doesn\`t appear to be modified'
}
} #end Process block
End
{
Write-Verbose -Message 'Add-ResourceToSCCMCollection: Ending the function'
}
}
#endregion
#region Remove-MachineNamefromSCCMCollection
function Remove-ResourceFromSCCMCollection
{
[CmdletBinding(DefaultParameterSetName='Device')]
[OutputType([PSObject])]
Param
(
# Enter the Computer Name
[Parameter(Mandatory,
helpmessage = 'Enter the ComputerNames array to remove from the Collection',
ValueFromPipeline,
ValueFromPipelineByPropertyName,
ParameterSetName='Device'
)]
[Alias('CN','computer')]
[String[]]
$ComputerName,
[Parameter(Mandatory,
helpmessage = 'Enter the ComputerNames array to remove from the Collection',
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
ParameterSetName='User'
)]
[Alias('SamAccountName','LogonName','Identity')]
[String[]]
$UserName,
#Specify the Collection ID
[Parameter(Mandatory,
ValueFromPipelineByPropertyName)]
[validatenotnullorempty()]
#[ValidatePattern('^[A-Za-z]{3}\w{5}$')]
[string]
$CollectionId,
# Specify the CIM Hash generated by Connect-SCCMServer
[Parameter(Mandatory)]
[validatenotnullorempty()]
[hashtable]$WMIHash
)
Begin
{
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Starting the function'
}
Process
{
try
{
$Collection = Get-WmiObject -Class SMS_Collection -Filter "CollectionID='$collectionid'" @WMIHash
Write-Verbose -Message "Remove-ResourceFromSCCMCollection: Queried the Collection $($collection.name) with CollectionId : $collectionid successfully"
$Collection.Get() #Invoke Get Method to get the Lazy Properties back
#create an empty array to hold QueryRules
$QueryRules = @()
$QueryRules = $Collection.CollectionRules | Where-Object -FilterScript {
$_.__Class -eq 'SMS_CollectionRuleQuery'
} #Take only QueryMembershipRule
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Queried the QueryRules on the Collection successfully'
}
catch
{
Write-Warning -Message 'Remove-ResourceFromSCCMCollection: Something went wrong while querying the Collection and the Collection Rules on it'
$LogCollection.Add("Remove-ResourceFromSCCMCollection: $_.exception ")
}
If ($QueryRules)
{
Foreach ($query in $QueryRules)
{
$queryexpression = $query.QueryExpression
#save the Original Length of the QuerExpression to later check if there were any changes made
$OriginalLength = $queryexpression.length
#region make changes to the each query and save them
switch -Exact ($PSCmdlet.ParameterSetName)
{
'User'
{
Foreach ($User in $UserName)
{
$templength = $queryexpression.length
#replaces machine name in the body and end of the query
$queryexpression = $queryexpression -replace ",`"$user`"", ''
$queryexpression = $queryexpression -replace "`"$User`",", ''
}
}
'Device'
{
Foreach ($computer in $ComputerName)
{
$templength = $queryexpression.length
#replaces machine name in the body and end of the query
$queryexpression = $queryexpression -replace ",`"$computer`"", ''
<#this takes care if the machine name is at starting of the queryexpression ...see the below query example
select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,
SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System
where SMS_R_System.NetbiosName in ("Machinename","OFPMXL93219T0",".....)
#>
$queryexpression = $queryexpression -replace "`"$computer`",", ''
}
}
}
#after the text manipulation, save the new query
$query.queryexpression = $queryexpression
#endregion
#region log the changes
if ($query.queryexpression.length -ne $OriginalLength)
{
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Taking the backup in C:\Temp\POSH_Deploy.csv'
#Now the QueryExpression has been modified...So before proceeeding take a backup
try
{
[pscustomobject]@{
'Collection' = $Collection.Name
'CollectionType' = $PSCmdlet.ParameterSetName
'CollectionID' = $CollectionId
'Action' = 'Remove'
'MachineNames' = [string]$ComputerName
'QueryName' = $query.RuleName
'QueryId' = $query.QueryId
'QueryExpression' = $query.QueryExpression
} | Export-Csv -NoTypeInformation -Path $PSdeployfile -Append
}
catch
{
$LogCollection.Add("Remove-ResourceFromSCCMCollection: $_.exception")
}
#endregion log the changes
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: The QueryExpression seems to be modified...saving the modified one now'
#region delete the previous Query Rule
#before deleting need to make sure the collection is ready
do
{
Start-Sleep -Seconds 1
}
until ((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1 )
#do a check before modifying the collection ---Is the Collection ready ?
if((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1)
{
if ( (Invoke-WmiMethod -Class SMS_CollectionRuleQuery -Name ValidateQuery -ArgumentList $query.QueryExpression @WMIHash).returnvalue -eq $true)
{
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Query Validation Succeeded'
try
{
$null = $Collection.DeleteMembershipRule($query)
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Invoked Method DeleteMembershipRule on the Collection'
$null = $Collection.RequestRefresh()
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Invoked Method RequestRefresh on the Collection'
}
catch
{
Write-Error -Message "Remove-ResourceFromSCCMCollection: Couldn't invoke method DeleteMembershipRule on the Collection with ID $collectionid"
$LogCollection.Add("Remove-ResourceFromSCCMCollection: Couldn't delete the QueryRule in the Collection")
}
}
else
{
Write-Verbose -Message 'Remove-ResourceFromSCCMCollection: Query you created is incorrect.'
$LogCollection.Add("QueryExpression couldn't be validated. Invalid WQL Syntax")
}
}
#endregion
#region Add a new Query Rule
#before deleting need to make sure the collection is ready
do
{
Start-Sleep -Seconds 1
}
until ((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1 )
#do a check before modifying the collection ---Is the Collection ready ?
if((Get-WmiObject -Query "Select CurrentStatus from SMS_Collection WHERE CollectionID='$collectionid'" @WMIHash).CurrentStatus -eq 1)
{
#means the collection is ready for the update
try
{
$null = $Collection.AddmembershipRule($query)
Write-Verbose -Message 'Invoked Method AddMembershipRule on the Collection'
$null = $Collection.RequestRefresh()
Write-Verbose -Message 'Invoked Method RequestRefresh on the Collection'
}
catch
{
Write-Warning -Message "Remove-ResourceFromSCCMCollection: Couldn't invoke method AddMembershipRule on the Collection with ID $collectionid"
$LogCollection.Add("Remove-ResourceFromSCCMCollection: $_.exception")