Unregister-ScriptCopRule.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
function Unregister-ScriptCopRule
{
    <#
    .Synopsis
        Unregisters a ScriptCop rule.
    .Description
        Unregisters a ScriptCop rule, prevent it from running
    .Example
        Unregister-ScriptCopRule -Name Test-DocumentationQuality
    .Link
        Register-ScriptCopRule
    #>

    [CmdletBinding(DefaultParameterSetName='Name')]
    param(
    # The name of the rule
    [Parameter(ParameterSetName='Name',Mandatory=$true)]
    [string]$Name,
    
    # The rule command
    [Parameter(ParameterSetName='Command',ValueFromPipeline=$true,Mandatory=$true)]
    [Management.Automation.CommandInfo]$Command
    )
    
    begin {
        # Declare rules structure if it does not exist
        if (-not $script:ScriptCopRules) {
            $script:ScriptCopRules = @{
                TestCommandInfo = @()
                TestCmdletInfo = @()
                TestScriptInfo = @()
                TestFunctionInfo = @()
                TestApplicationInfo=  @()
                TestModuleInfo = @()
                TestScriptToken = @()
                TestHelpContent = @()
            }
        }
    }
    
    process {
        if ($psCmdlet.ParameterSetName -eq 'Name') {
            #region Locate and Remove Rule by Name
            if ($script:ScriptCopRules) {
                @($script:ScriptCopRules | 
                    ForEach-Object { 
                        foreach ($v in $_.Values) { $V }
                    }) |
                    Where-Object { 
                        $_.Name -eq $Name
                    } |                    
                    Unregister-ScriptCopRule 
                    
            }
            #endregion
        } elseif ($psCmdlet.ParameterSetName -eq 'Command') {
             #region Locate and Remove Command
             $toRemove = $script:ScriptCopRules.GetEnumerator() | 
                    Where-Object { 
                        $_.Value -contains $Command
                    } 
                    
            if ($toRemove) {
                foreach ($tr in $toRemove) { 
                    $script:ScriptCopRules[$tr.Key] = @($script:ScriptCopRules[$tr.Key] | Where-Object { $_ -ne $Command })
                }            
            }
            #endregion
        }
        
        # Output the new rules to debug when completed.
        Write-Debug ($scriptCopRules | Out-String)
    }
}