GPWmiFilter.psm1

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\GPWmiFilter.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName GPWmiFilter.Import.DoDotSource -Fallback $false
if ($GPWmiFilter_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName GPWmiFilter.Import.IndividualFiles -Fallback $false
if ($GPWmiFilter_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    if ($doDotSource) { . (Resolve-Path $Path).ProviderPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText((Resolve-Path $Path).ProviderPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
function Get-DomainController
{
<#
    .SYNOPSIS
        Returns a specific domain controller.
     
    .DESCRIPTION
        Helper function that resolves the server parameter into a specific domain controller to operate against.
        If the server parameter is given an actual domain controller, it will try to contact it and return its name.
        If given a domain name, it will contact an arbitrary domain controller and return its name.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller or domain.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .EXAMPLE
        PS C:\> Get-DomainController -Server 'contoso.com'
     
        Returns a domain controller of the domain 'contoso.com'
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Server,
        
        [AllowNull()]
        [System.Management.Automation.PSCredential]
        $Credential
    )
    
    $adParameters = @{
        Server        = $Server
        ErrorAction = 'Stop'
    }
    if ($Credential -and ($Credential -ne [System.Management.Automation.PSCredential]::Empty))
    {
        $adParameters['Credential'] = $Credential
    }
    
    try { $controller = (Get-ADDomainController @adParameters).HostName }
    catch { throw }
    Write-PSFMessage -Level Debug -String 'Get-DomainController.DCFound' -StringValues $Server, $controller
    $controller
}

function Resolve-PolicyName
{
<#
    .SYNOPSIS
        Simple helper tool for parsing GPO object/name input.
     
    .DESCRIPTION
        Simple helper tool for parsing GPO object/name input.
        Returns name or id.
        ONLY use in pipeline.
     
    .PARAMETER InputObject
        The object to parse.
     
    .EXAMPLE
        PS C:\> $Policy | Resolve-PolicyName
     
        Returns IDs or Names of all policy items in $Policy
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )
    
    process
    {
        if ($null -eq $InputObject) { return }
        if ($InputObject.GetType().FullName -eq 'Microsoft.GroupPolicy.Gpo') { return $InputObject.Id -as [string] }
        if ($InputObject.Id) { return $InputObject.Id -as [string] }
        if ($InputObject.DisplayName) { return $InputObject.DisplayName -as [string] }
        $InputObject -as [string]
    }
}

function Clear-GPWmiFilterAssignment
{
<#
    .SYNOPSIS
        Clears a GPO of its assigned WMI Filter.
     
    .DESCRIPTION
        Clears a GPO of its assigned WMI Filter.
     
    .PARAMETER Policy
        The name of the GPO to clear of its assigned WMI Filter.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Get-GPO -All | Clear-GPWmiFilterAssignment
     
        Clear all WMI Filters from all GPOs.
#>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)]
        [Alias('Id', 'DisplayName')]
        $Policy,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Clear-GPWmiFilterAssignment.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
        
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    process
    {
        foreach ($policyItem in ($Policy | Resolve-PolicyName))
        {
            $gpoObject = Get-ADObject @adParameters -LDAPFilter "(&(objectClass=groupPolicyContainer)(|(cn=$($policyItem))(cn={$($policyItem)})(displayName=$($policyItem))))"
            
            if (-not $gpoObject)
            {
                Write-PSFMessage -Level Warning -String 'Clear-GPWmiFilterAssignment.GPONotFound' -StringValues $policyItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Clear-GPWmiFilterAssignment.UpdatingGPO' -ActionStringValues $policyItem, $gpoObject -Target $policyItem -ScriptBlock {
                $gpoObject | Set-ADObject @adParameters -Clear 'gPCWQLFilter'
            } -Continue -PSCmdlet $PSCmdlet -EnableException $EnableException.ToBool()
        }
    }
}

function Get-GPWmiFilter
{
<#
    .SYNOPSIS
        Get a WMI filter in current domain
     
    .DESCRIPTION
        The Get-GPWmiFilter function query WMI filter(s) in current domain with specific name or GUID.
     
    .PARAMETER Name
        The name of WMI filter you want to query out.
        Default Value: '*'
     
    .PARAMETER Guid
        The guid of WMI filter you want to query out.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .EXAMPLE
        PS C:\> Get-GPWmiFilter -Name 'Virtual Machines'
         
        Get WMI filter(s) with the name 'Virtual Machines'
     
    .EXAMPLE
        PS C:\> Get-GPWmiFilter
         
        Get all WMI filters in current domain
#>

    [CmdletBinding(DefaultParameterSetName = 'ByName')]
    param
    (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = "ByName")]
        [ValidateNotNull()]
        [string[]]
        $Name = "*",
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "ByGUID")]
        [ValidateNotNull()]
        [Guid[]]
        $Guid,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Get-GPWmiFilter.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
        
        $parameters = @{
            Properties = "msWMI-Name", "msWMI-Parm1", "msWMI-Parm2", "msWMI-Author", "msWMI-ID", "Modified", 'nTSecurityDescriptor'
            Server = $PSBoundParameters.Server
        }
        if (Test-PSFParameterBinding -ParameterName Credential) { $parameters['Credential'] = $Credential }
        
        $selectProperties = @(
            '"msWMI-Name" as Name'
            '"msWMI-Author" as Author'
            '"msWMI-Parm1" as Description'
            '"msWMI-ID".Trim("{}") to GUID as ID'
            'Modified'
            '"msWMI-Parm2" as Filter'
            'DistinguishedName'
            'nTSecurityDescriptor.Owner as SecOwner'
            'nTSecurityDescriptor.Access as SecAccess'
            'nTSecurityDescriptor as SecACL'
        )
        [System.Collections.ArrayList]$foundPolicies = @()
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        
        if ($Guid)
        {
            foreach ($guidItem in $Guid)
            {
                Write-PSFMessage -String 'Get-GPWmiFilter.SearchGuid' -StringValues $guidItem -Level Debug
                $ldapFilter = "(&(objectClass=msWMI-Som)(Name={$guidItem}))"
                Get-ADObject @parameters -LDAPFilter $ldapFilter | Select-PSFObject -Property $selectProperties -TypeName 'GroupPolicy.WMIFilter' | Where-Object {
                    if ($foundPolicies -notcontains $_.ID)
                    {
                        $null = $foundPolicies.Add($_.ID)
                        return $true
                    }
                }
            }
        }
        elseif ($Name)
        {
            foreach ($nameItem in $Name)
            {
                Write-PSFMessage -String 'Get-GPWmiFilter.SearchName' -StringValues $nameItem -Level Debug
                $ldapFilter = "(&(objectClass=msWMI-Som)(msWMI-Name=$nameItem))"
                Get-ADObject @parameters -LDAPFilter $ldapFilter | Select-PSFObject -Property $selectProperties -TypeName 'GroupPolicy.WMIFilter' | Where-Object {
                    if ($foundPolicies -notcontains $_.ID)
                    {
                        $null = $foundPolicies.Add($_.ID)
                        return $true
                    }
                }
            }
        }
    }
}


function New-GPWmiFilter
{
<#
    .SYNOPSIS
        Create a new WMI filter for Group Policy with given name, WQL query and description.
     
    .DESCRIPTION
        The New-GPWmiFilter function create an AD object for WMI filter with specific name, WQL query expressions and description.
        With -PassThru switch, it output the WMIFilter instance which can be assigned to GPO.WMIFilter property.
     
    .PARAMETER Name
        The name of new WMI filter.
     
    .PARAMETER Filter
        The wmi filter query to use as condition for the filter.
     
    .PARAMETER Expression
        The expression(s) of WQL query in new WMI filter. Pass an array to this parameter if multiple WQL queries applied.
     
    .PARAMETER Description
        The description text of the WMI filter (optional).
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        New-GPWmiFilter -Name 'Virtual Machines' -Filter 'SELECT * FROM Win32_ComputerSystem WHERE Model = "Virtual Machine"' -Description 'Only apply on virtual machines'
         
        Create a WMI filter to apply GPO only on virtual machines
     
    .EXAMPLE
        Get-GPWmiFilter -Server contoso.com | New-GPWmiFilter -Server fabrikam.com
     
        Copies all WMI Filters from the domain contoso.com to the domain fabrikam.com
     
    .EXAMPLE
        $filter = New-GPWmiFilter -Name 'Workstation 32-bit' -Expression 'SELECT * FROM WIN32_OperatingSystem WHERE ProductType=1', 'SELECT * FROM Win32_Processor WHERE AddressWidth = "32"' -PassThru
        $gpo = New-GPO -Name "Test GPO"
        $gpo.WmiFilter = $filter
         
        Create a WMI filter for 32-bit work station and link it to a new GPO named "Test GPO".
#>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
        [ValidateNotNull()]
        [string]
        $Name,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)]
        [ValidateNotNull()]
        [Alias('Expression')]
        [string[]]
        $Filter,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [string]
        $Description,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        $adParameters = @{
            Server        = $Server
            ErrorAction = 'Stop'
        }
        if (Test-PSFParameterBinding -ParameterName Credential) { $adParameters['Credential'] = $Credential }
        
        try
        {
            $namingContext = (Get-ADRootDSE @adParameters).DefaultNamingContext
            # Resolve to dedicated server to ensure repeated calls are executed against same machine
            $adParameters.Server = (Get-ADDomainController @adParameters).HostName
        }
        catch
        {
            Stop-PSFFunction -String 'New-GPWmiFilter.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        if ($Filter.Count -lt 1)
        {
            Stop-PSFFunction -String 'New-GPWmiFilter.NoFilter' -EnableException $EnableException
            return
        }
        
        $wmiGuid = "{$([System.Guid]::NewGuid())}"
        $creationDate = (Get-Date).ToUniversalTime().ToString("yyyyMMddhhmmss.ffffff-000")
        $filterString = "{0};" -f $Filter.Count.ToString()
        $Filter | ForEach-Object {
            $filterString += "3;10;{0};WQL;root\CIMv2;{1};" -f $_.Length, $_
        }
        $attributes = @{
            "showInAdvancedViewOnly" = "TRUE"
            "msWMI-Name"             = $Name
            "msWMI-Parm1"             = $Description
            "msWMI-Parm2"             = $filterString
            "msWMI-Author"             = (Get-PSFConfigValue -FullName 'GPWmiFilter.Author' -Fallback "$($env:USERNAME)@$($env:USERDNSDOMAIN)")
            "msWMI-ID"                 = $wmiGuid
            "instanceType"             = 4
            "distinguishedname"         = "CN=$wmiGuid,CN=SOM,CN=WMIPolicy,CN=System,$namingContext"
            "msWMI-ChangeDate"         = $creationDate
            "msWMI-CreationDate"     = $creationDate
        }
        
        $paramNewADObject = @{
            OtherAttributes = $attributes
            Name            = $wmiGuid
            Type            = "msWMI-Som"
            Path            = "CN=SOM,CN=WMIPolicy,CN=System,$namingContext"
        }
        $paramNewADObject += $adParameters
        Invoke-PSFProtectedCommand -ActionString 'New-GPWmiFilter.CreatingFilter' -ActionStringValues $Name -ScriptBlock {
            New-ADObject @paramNewADObject
            Get-GPWmiFilter -Guid $wmiGuid @adParameters
        } -Target $Name -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet
    }
}


function Remove-GPWmiFilter
{
<#
    .SYNOPSIS
        Remove a WMI filter from current domain
     
    .DESCRIPTION
        The Remove-GPWmiFilter function remove WMI filter(s) in current domain with specific name or GUID.
     
    .PARAMETER Guid
        The guid of WMI filter you want to remove.
     
    .PARAMETER Name
        The name of WMI filter you want to remove.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        Remove-GPWmiFilter -Name 'Virtual Machines'
         
        Remove the WMI filter with name 'Virtual Machines'
#>

    [CmdletBinding(DefaultParametersetName = "ByName", SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = "ByGUID")]
        [ValidateNotNull()]
        [Guid[]]
        $Guid,
        
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = "ByName")]
        [ValidateNotNull()]
        [string[]]
        $Name,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Remove-GPWmiFilter.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
        
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        $getParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Guid, Name, Server, Credential
        foreach ($wmiFilter in (Get-GPWmiFilter @getParameters))
        {
            Invoke-PSFProtectedCommand -ActionString Remove-GPWmiFilter.Delete -ActionStringValues $wmiFilter.Name -Target $wmiFilter.ID -ScriptBlock {
                Remove-ADObject -Identity $wmiFilter.DistinguishedName @adParameters -Confirm:$false -ErrorAction Stop
            } -EnableException $EnableException.ToBool() -Continue -PSCmdlet $PSCmdlet
        }
    }
}


function Rename-GPWmiFilter
{
<#
    .SYNOPSIS
        Get a WMI filter in current domain and rename it
     
    .DESCRIPTION
        The Rename-GPWmiFilter function query WMI filter in current domain with specific name or GUID and then change it to a new name.
     
    .PARAMETER Name
        The name of WMI filter you want to query out.
     
    .PARAMETER Guid
        The guid of WMI filter you want to query out.
     
    .PARAMETER NewName
        The new name of WMI filter.
     
    .PARAMETER PassThru
        Output the renamed WMI filter instance with this switch.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        Rename-GPWmiFilter -Name 'Workstations' -NewName 'Client Machines'
         
        Rename WMI filter "Workstations" to "Client Machines"
#>

    [CmdletBinding(DefaultParameterSetName = 'ByName', SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = "ByName")]
        [ValidateNotNull()]
        [string[]]
        $Name,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "ByGUID")]
        [ValidateNotNull()]
        [Guid[]]
        $Guid,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)]
        [ValidateNotNull()]
        [string]
        $NewName,
        
        [switch]
        $PassThru,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Rename-GPWmiFilter.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
    }
    process
    {
        #region Validation and Prepare
        if (Test-PSFFunctionInterrupt) { return }
        
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Name, Guid, Credential, Server
        #endregion Validation and Prepare
        
        foreach ($wmiFilter in (Get-GPWmiFilter @parameters))
        {
            Write-PSFMessage -String 'Rename-GPWmiFilter.RenamingFilter' -StringValues $wmiFilter.Name, $NewName, $wmiFilter.DistinguishedName -Target $wmiFilter.ID
            
            #region Validate Necessity
            if ($wmiFilter.Name -eq $NewName)
            {
                Write-PSFMessage -String 'Rename-GPWmiFilter.NoChangeNeeded' -StringValues $wmiFilter.Name, $NewName, $wmiFilter.DistinguishedName
                if ($PassThru) { $wmiFilter }
                continue
            }
            #endregion Validate Necessity
            
            #region Calculate AD Attribute Updates
            $adAttributes = @{
                "msWMI-Author" = (Get-PSFConfigValue -FullName 'GPWmiFilter.Author' -Fallback "$($env:USERNAME)@$($env:USERDNSDOMAIN)")
                "msWMI-ChangeDate" = (Get-Date).ToUniversalTime().ToString("yyyyMMddhhmmss.ffffff-000")
                "msWMI-Name"   = $NewName
            }
            #endregion Calculate AD Attribute Updates
            
            #region Perform Change
            $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
            Invoke-PSFProtectedCommand -ActionString 'Rename-GPWmiFilter.PerformingRename' -ActionStringValues $wmiFilter.Name, $NewName, $wmiFilter.DistinguishedName -ScriptBlock {
                Set-ADObject @adParameters -Identity $wmiFilter.DistinguishedName -Replace $adAttributes -ErrorAction Stop
            } -Target $wmiFilter.ID -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue
            
            if ($PassThru)
            {
                $getParameters = $adParameters.Clone()
                $getParameters['Guid'] = $wmiFilter.ID
                Get-GPWmiFilter @getParameters
            }
            #endregion Perform Change
        }
    }
}


function Set-GPWmiFilter
{
<#
    .SYNOPSIS
        Update the settings of a WMI filter.
     
    .DESCRIPTION
        Update the settings of a WMI filter.
     
    .PARAMETER Name
        The name of WMI filter you want to query out.
     
    .PARAMETER Guid
        The guid of WMI filter you want to query out.
     
    .PARAMETER Filter
        The expression(s) of WQL query in new WMI filter. Pass an array to this parameter if multiple WQL queries applied.
     
    .PARAMETER Description
        The description text of the WMI filter.
     
    .PARAMETER PassThru
        Output the updated WMI filter instance with this switch.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        Set-GPWmiFilter -Name 'Workstations' -Filter 'SELECT * FROM Win32_OperatingSystem WHERE ProductType = "1"'
         
        Set WMI filter named with "Workstations" to specific WQL query
     
    .EXAMPLE
        Get-GPWmiFilter -Server contoso.com | Set-GPWmiFilter -Server fabrikam.com
     
        Updates changes made to the wmi filters in the domain contoso.com to the wmi filters in the domain fabrikam.com.
#>

    [CmdletBinding(DefaultParameterSetName = 'ByName', SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = "ByName")]
        [string[]]
        $Name,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "ByGUID")]
        [Guid[]]
        $Guid,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [Alias('Expression')]
        [string[]]
        $Filter,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [string]
        $Description,
        
        [switch]
        $PassThru,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Set-GPWmiFilter.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
    }
    process
    {
        #region Validation and Prepare
        if (Test-PSFFunctionInterrupt) { return }
        
        if (Test-PSFParameterBinding -ParameterName Filter, Description -Not)
        {
            Stop-PSFFunction -String 'Set-GPWmiFilter.NoChangeParameters' -StringValues 'Filter', 'Description' -EnableException $EnableException -Cmdlet $PSCmdlet -Category InvalidArgument
            return
        }
        
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Name, Guid, Credential, Server
        #endregion Validation and Prepare
        
        foreach ($wmiFilter in (Get-GPWmiFilter @parameters))
        {
            Write-PSFMessage -String 'Set-GPWmiFilter.UpdatingFilter' -StringValues $wmiFilter.Name, $wmiFilter.DistinguishedName -Target $wmiFilter.ID
            #region Calculate AD Attribute Updates
            $adAttributes = @{
                "msWMI-Author"       = (Get-PSFConfigValue -FullName 'GPWmiFilter.Author' -Fallback "$($env:USERNAME)@$($env:USERDNSDOMAIN)")
                "msWMI-ChangeDate" = (Get-Date).ToUniversalTime().ToString("yyyyMMddhhmmss.ffffff-000")
            }
            $changeHappened = $false
            
            #region Calculating Filter
            if ($Filter)
            {
                # If receiving a fully valid filter string (e.g.: When updating from one Forest to another)
                if ($Filter -match '3;10;\d+;WQL')
                {
                    $adAttributes['msWMI-Parm2'] = $Filter
                }
                else
                {
                    $filterString = '{0};' -f $Filter.Count
                    foreach ($filterItem in $Filter)
                    {
                        $filterString += "3;10;{0};WQL;root\CIMv2;{1};" -f $filterItem.Length, $filterItem
                    }
                    $adAttributes['msWMI-Parm2'] = $filterString
                }
                if ($adAttributes['msWMI-Parm2'] -ne $wmiFilter.Filter) { $changeHappened = $true }
            }
            #endregion Calculating Filter
            #region Adding Description
            if ($Description)
            {
                $adAttributes['msWMI-Parm1'] = $Description
                if ($Description -ne $wmiFilter.Description) { $changeHappened = $true }
            }
            #endregion Adding Description
            #endregion Calculate AD Attribute Updates
            
            #region Validate Necessity
            if (-not $changeHappened)
            {
                Write-PSFMessage -String 'Set-GPWmiFilter.NoChangeNeeded' -StringValues $wmiFilter.Name, $wmiFilter.DistinguishedName
                if ($PassThru) { $wmiFilter }
                continue
            }
            #endregion Validate Necessity
            
            #region Perform Change
            $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
            Invoke-PSFProtectedCommand -ActionString 'Set-GPWmiFilter.PerformingUpdate' -ActionStringValues $wmiFilter.Name, $wmiFilter.DistinguishedName -ScriptBlock {
                Set-ADObject @adParameters -Identity $wmiFilter.DistinguishedName -Replace $adAttributes -ErrorAction Stop
            } -Target $wmiFilter.ID -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue
            
            if ($PassThru)
            {
                $getParameters = $adParameters.Clone()
                $getParameters['Guid'] = $wmiFilter.ID
                Get-GPWmiFilter @getParameters
            }
            #endregion Perform Change
        }
    }
}


function Set-GPWmiFilterAssignment
{
<#
    .SYNOPSIS
        Assigns WMI Filters to GPOs.
     
    .DESCRIPTION
        Assigns WMI Filters to GPOs.
     
    .PARAMETER Policy
        The Group Policy Object to modify.
     
    .PARAMETER Filter
        The Filter to Apply.
     
    .PARAMETER Server
        The server to contact.
        Specify the DNS Name of a Domain Controller.
     
    .PARAMETER Credential
        The credentials to use to contact the targeted server.
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-GPO -Name '01_A_OU_1' | Set-GPWmiFilterAssignment -Filter 'Windows 10'
     
        Assigns the WMI Filter "WIndows 10" to the GPO "01_A_OU_1"
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('Id', 'DisplayName')]
        $Policy,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        $Filter,
        
        [string]
        $Server = $env:USERDNSDOMAIN,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Resolve Server
        try { $PSBoundParameters.Server = Get-DomainController -Server $Server -Credential $Credential }
        catch
        {
            Stop-PSFFunction -String 'Set-GPWmiFilterAssignment.FailedADAccess' -StringValues $Server -EnableException $EnableException -ErrorRecord $_
            return
        }
        #endregion Resolve Server
        
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        $domainName = (Get-ADDomain @adParameters).DNSRoot
        
        #region Handle Explicit Filter input
        $filterExplicit = $false
        if (Test-PSFParameterBinding -Mode Explicit -ParameterName 'Filter')
        {
            if ($Filter.PSObject.TypeNames -eq 'GroupPolicy.WMIFilter')
            {
                $filterObject = $Filter
            }
            elseif ($Filter -as [System.Guid])
            {
                $filterObject = Get-GPWmiFilter @adParameters -Guid $Filter
            }
            else { $filterObject = Get-GPWmiFilter @adParameters -Name $Filter }
            
            if (-not $filterObject)
            {
                Stop-PSFFunction -String 'Set-GPWmiFilterAssignment.NoFilter' -StringValues $Filter -EnableException $EnableException
                return
            }
            if ($filterObject.Count -gt 1)
            {
                Stop-PSFFunction -String 'Set-GPWmiFilterAssignment.TooManyFilter' -StringValues $Filter -EnableException $EnableException
                return
            }
            $filterExplicit = $true
            $filterString = '[{0};{{{1}}};0]' -f $domainName, $filterObject.ID.ToString().ToUpper()
        }
        #endregion Handle Explicit Filter input
    }
    process
    {
        if (Test-PSFFunctionInterrupt) { return }
        
        #region Piped Filter Input
        if (-not $filterExplicit)
        {
            if ($Filter.PSObject.TypeNames -eq 'GroupPolicy.WMIFilter')
            {
                $filterObject = $Filter
            }
            elseif ($Filter -as [System.Guid])
            {
                $filterObject = Get-GPWmiFilter @adParameters -Guid $Filter
            }
            else { $filterObject = Get-GPWmiFilter @adParameters -Name $Filter }
            
            if (-not $filterObject)
            {
                Stop-PSFFunction -String 'Set-GPWmiFilterAssignment.NoFilter' -StringValues $Filter -EnableException $EnableException
                return
            }
            if ($filterObject.Count -gt 1)
            {
                Stop-PSFFunction -String 'Set-GPWmiFilterAssignment.TooManyFilter' -StringValues $Filter -EnableException $EnableException
                return
            }
            $filterString = '[{0};{{{1}}};0]' -f $domainName, $filterObject.ID.ToString().ToUpper()
        }
        #endregion Piped Filter Input
        
        foreach ($policyItem in ($Policy | Resolve-PolicyName))
        {
            $gpoObject = Get-ADObject @adParameters -LDAPFilter "(&(objectClass=groupPolicyContainer)(|(cn=$($policyItem))(cn={$($policyItem)})(displayName=$($policyItem))))"
            
            if (-not $gpoObject)
            {
                Write-PSFMessage -Level Warning -String 'Set-GPWmiFilterAssignment.GPONotFound' -StringValues $policyItem
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Set-GPWmiFilterAssignment.UpdatingGPO' -ActionStringValues $filterObject.Name, $policyItem, $gpoObject -Target $policyItem -ScriptBlock {
                $gpoObject | Set-ADObject @adParameters -Replace @{ gPCWQLFilter = $filterString }
            } -Continue -PSCmdlet $PSCmdlet -EnableException $EnableException.ToBool()
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'GPWmiFilter' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'GPWmiFilter' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'GPWmiFilter' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'GPWmiFilter' -Name 'Author' -Value "$($env:USERNAME)@$($env:USERDNSDOMAIN)" -Initialize -Validation 'string' -Description 'The name to use as Author when updating a WMI Filter.'

Register-PSFTeppScriptblock -Name 'GPWmiFilter.Filter' -ScriptBlock {
    $adParameters = @{ }
    if ($fakeBoundParameter.Server) { $adParameters['Server'] = $fakeBoundParameter.Server }
    if ($fakeBoundParameter.Credential) { $adParameters['Credential'] = $fakeBoundParameter.Credential }
    
    (Get-GPWmiFilter @adParameters).Name
}


Register-PSFTeppArgumentCompleter -Command Get-GPWmiFilter -Parameter Name -Name 'GPWmiFilter.Filter'
Register-PSFTeppArgumentCompleter -Command Remove-GPWmiFilter -Parameter Name -Name 'GPWmiFilter.Filter'
Register-PSFTeppArgumentCompleter -Command Rename-GPWmiFilter -Parameter Name -Name 'GPWmiFilter.Filter'
Register-PSFTeppArgumentCompleter -Command Set-GPWmiFilter -Parameter Name -Name 'GPWmiFilter.Filter'

Register-PSFTeppArgumentCompleter -Command Set-GPWmiFilterAssignment -Parameter Filter -Name 'GPWmiFilter.Filter'

New-PSFLicense -Product 'GPWmiFilter' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-01-10") -Text @"
Copyright (c) 2019 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code