Public/Invoke-Vester.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
function Invoke-Vester {
    <#
    .SYNOPSIS
    Test and fix configuration drift in your VMware vSphere environment.
 
    .DESCRIPTION
    Invoke-Vester will run each test it finds and report on discrepancies.
    It compares actual values against the values you supply in a config file,
    and can fix them immediately if you include the -Remediate parameter.
 
    If you are not already connected to the vCenter server defined in the
    config file, Invoke-Vester will prompt for credentials to connect to it.
 
    Invoke-Vester then calls Pester to run each test file. The test files
    leverage PowerCLI to gather values for comparison/remediation.
 
    .EXAMPLE
    Invoke-Vester -Verbose
    Using the default config file at \Vester\Configs\Config.json,
    Vester will run all included tests inside of \Vester\Tests\.
    Verbose output will be displayed on the screen.
    It outputs a report to the host of all passed and failed tests.
 
    .EXAMPLE
    Invoke-Vester -Config C:\Tests\Config.json -Test C:\Tests\
    Vester runs all *.Vester.ps1 files found underneath the C:\Tests\ directory,
    and compares values to the config file in the same location.
    It outputs a report to the host of all passed and failed tests.
 
    .EXAMPLE
    $DNS = Get-VesterTest -Path Z:\ -Name *dns*
    PS C:\>(Get-ChildItem -Path Z:\ -Filter *.json).FullName | Invoke-Vester -Test $DNS
 
    Get all Vester tests at Z:\ with 'dns' in the name; store in variable $DNS.
    Then, pipe all *.json files at the root of Z: into the -Config parameter.
    Each config file piped in will run through all $DNS tests found.
 
    .EXAMPLE
    Invoke-Vester -Test (Get-VesterTest -Scope VM) -Remediate -WhatIf
    Run Vester with all VM tests included with the module.
    For all tests that fail against the values in \Configs\Config.json,
    -Remediate attempts to immediately fix them to match your defined config.
    -WhatIf prevents remediation, and instead reports what would have changed.
 
    .EXAMPLE
    Invoke-Vester -Config .\Config-Dev.json -Remediate
    Run all \Vester\Tests\ files, and compare values to those defined within
    the Config-Dev.json file at the current location.
    For all failed tests, -Remediate attempts to immediately correct your
    infrastructure to match the previously defined values in your config file.
 
    .EXAMPLE
    Invoke-Vester -XMLOutputFile .\vester.xml
    Runs Vester with the default config and test files.
    Uses Pester to send test results in NUnitXML format to vester.xml
    at your current folder location.
    Useful to supply to a report generator for HTML reports.
 
    .INPUTS
    [System.Object]
    Accepts piped input (optional multiple objects) for parameter -Config
 
    .NOTES
    This command relies on the Pester and PowerCLI modules for testing.
 
    "Get-Help about_Vester" for more information.
 
    .LINK
    https://wahlnetwork.github.io/Vester
 
    .LINK
    https://github.com/WahlNetwork/Vester
    #>

    [CmdletBinding(SupportsShouldProcess = $true,
                   ConfirmImpact = 'Medium')]
    # ^ that passes -WhatIf through to other tests
    param (
        # Optionally define a different config file to use
        # Defaults to \Vester\Configs\Config.json
        [Parameter(ValueFromPipeline = $True,
                   ValueFromPipelinebyPropertyName=$True)]
        [ValidateScript({
            If ($_.FullName) {Test-Path $_.FullName}
            Else {Test-Path $_}
        })]
        [Alias('FullName')]
        [object[]]$Config = "$(Split-Path -Parent $PSScriptRoot)\Configs\Config.json",

        # Optionally define the file/folder of test file(s) to call
        # Defaults to \Vester\Tests\, grabbing all tests recursively
        # All test files must be named *.Vester.ps1
        [ValidateScript({
            If ($_.FullName) {Test-Path $_.FullName}
            Else {Test-Path $_}
        })]
        [Alias('Path','Script')]
        [object[]]$Test = (Get-VesterTest -Simple),

        # Optionally fix all config drift that is discovered
        # Defaults to false (disabled)
        [switch]$Remediate = $false,

        # Optionally save Pester output in NUnitXML format to a specified path
        # Specifying a path automatically triggers Pester in NUnitXML mode
        [ValidateScript({Test-Path (Split-Path $_ -Parent)})]
        [object]$XMLOutputFile,

        # Optionally returns the Pester result as an object containing the information about the whole test run, and each test
        # Defaults to false (disabled)
        [switch]$PassThru = $false
    )

    PROCESS {
        # -Test should accept directories and objects
        If ($Test[0] -notlike '*.Vester.ps1') {
            If ($Test[0].FullName) {
                # Strip Get-Item/Get-ChildItem/Get-VesterTest object to path only
                $Test = $Test.FullName
            } Else {
                # This is a directory. Get the Vester tests here
                $Test = $Test | Get-VesterTest -Simple
            }
        }

        ForEach ($ConfigFile in $Config) {
            # Gracefully handle Get-Item/Get-ChildItem
            If ($ConfigFile.FullName) {
                $ConfigFile = $ConfigFile.FullName
            }
            Write-Verbose -Message "Processing Config file $ConfigFile"

            # Load the defined $cfg values to test
            # -Raw needed for PS v3/v4
            $cfg = Get-Content $ConfigFile -Raw | ConvertFrom-Json

            If (-not $cfg) {
                throw "Valid config data not found at path '$ConfigFile'. Exiting"
            }

            # Check for established session to desired vCenter server
            If ($cfg.vcenter.vc -notin $global:DefaultVIServers.Name) {
                Try {
                    # Attempt connection to vCenter; prompts for credentials if needed
                    Write-Verbose "No active connection found to configured vCenter '$($cfg.vcenter.vc)'. Connecting"
                    $VIServer = Connect-VIServer -Server $cfg.vcenter.vc -ErrorAction Stop
                } Catch {
                    # If unable to connect, stop
                    throw "Unable to connect to configured vCenter '$($cfg.vcenter.vc)'. Exiting"
                }
            } Else {
                $VIServer = $global:DefaultVIServers | Where {$_.Name -match $cfg.vcenter.vc}
            }
            Write-Verbose "Processing against vCenter server '$($cfg.vcenter.vc)'"

            # Call Invoke-Pester based on the parameters supplied
            # Runs VesterTemplate.Tests.ps1, which constructs the .Vester.ps1 test files
            If ($XMLOutputFile) {
                Invoke-Pester -OutputFormat NUnitXml -OutputFile $XMLOutputFile -Script @{
                    Path = "$(Split-Path -Parent $PSScriptRoot)\Private\Template\VesterTemplate.Tests.ps1"
                    Parameters = @{
                        Cfg       = $cfg
                        TestFiles = $Test
                        Remediate = $Remediate
                    }
                } # Invoke-Pester
            } ElseIf ($PassThru) {
                Invoke-Pester -PassThru -Script @{
                    Path = "$(Split-Path -Parent $PSScriptRoot)\Private\Template\VesterTemplate.Tests.ps1"
                    Parameters = @{
                        Cfg       = $cfg
                        TestFiles = $Test
                        Remediate = $Remediate
                    }
                } # Invoke-Pester
            } Else {
                Invoke-Pester -Script @{
                    Path = "$(Split-Path -Parent $PSScriptRoot)\Private\Template\VesterTemplate.Tests.ps1"
                    Parameters = @{
                        Cfg       = $cfg
                        TestFiles = $Test
                        Remediate = $Remediate
                    }
                } # Invoke-Pester
            } #If XML

            # In case multiple config files were provided and some aren't valid
            $cfg = $null
        } #ForEach Config
    } #Process
} #function